Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending json with .NET HttpClient to a WebAPI server

I'm trying to send json via POST using HttpClient to my webservice.

Send method is really simple:

HttpClient _httpClient = new HttpClient(); 
public async Task<HttpStatusCode> SendAsync(Data data)
    {
        string jsonData = JsonConvert.SerializeObject(data);
        var content = new StringContent(
                jsonData,
                Encoding.UTF8,
                "application/json");
            HttpResponseMessage response = await _httpClient.PostAsync(_url, content);

            return response.StatusCode;
    }

On the server side I have the WebAPI controller with following method:

    [HttpPost]
    [ActionName("postdata")]
    public async Task<HttpResponseMessage> PostData([FromBody] string jsonParam)
    {
            /// here the jsonParam is null when receiving from HttpClient. 
            // jsonParam gets deserialized, etc
    }

The jsonParam in this method is null. The jsonData is good, if I copy and paste it into a request sender (I use Postman) everything is successful.

It's about how I construct the content and use the HttpClient but I can't figure out what's wrong.

Can anyone see the issue?

like image 600
Dan Dinu Avatar asked Sep 29 '22 21:09

Dan Dinu


1 Answers

Since you are trying to POST json, you can add a reference to System.Net.Http.Formatting and post "Data" directly without having to serialize it and create a StringContent.

public async Task<HttpStatusCode> SendAsync(Data data)
{
        HttpResponseMessage response = await _httpClient.PostAsJsonAsync(_url, content);

        return response.StatusCode;
}

On your receiving side, you can receive the "Data" type directly.

 [HttpPost]
    [ActionName("postdata")]
    public async Task<HttpResponseMessage> PostData(Data jsonParam)
    {

    }

More info on these HttpClientExtensions methods can be found here - http://msdn.microsoft.com/en-us/library/hh944521(v=vs.118).aspx

like image 156
govin Avatar answered Oct 03 '22 02:10

govin