Monday, September 26, 2016

Post complex objects as parameters to web api controllers

I have an API project and want to call a web method asynchroneously from client project.

The easiest way to do this is to use code like

HttpClient.PostAsJsonAsync<T>(T value) sends application/json
HttpClient.PostAsXmlAsync<T>(T value) sends application/xml

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

Copied from http://stackoverflow.com/questions/10304863/how-to-use-system-net-httpclient-to-post-a-complex-type

To call a method with simple parameters use

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

Copied from http://stackoverflow.com/questions/27376133/c-httpclient-with-post-parameters

To debug the posted JSON, use JObject parameter type at the web api method
/* Production */
public HttpResponseMessage TrackingRecord([FromBody] TrackingRecord record)
{
    ....
}

/* Debugging */
public HttpResponseMessage TrackingRecord([FromBody] JObject json)
{
    ....
}
Copied from http://forums.asp.net/t/2042177.aspx?Posting+Json+from+C+app+to+Web+API+fails

No comments:

SSL Error - The connection for this site is not secure

 After cloning a git repo of dot net framework website and trying to run it all I could see was this error Turns out the fix was to simply e...