Dan Dinu
Dan Dinu

Reputation: 33438

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?

Upvotes: 5

Views: 10910

Answers (2)

govin
govin

Reputation: 6733

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

Upvotes: 4

YK1
YK1

Reputation: 7622

When posting single simple type, you need special syntax on post body:

=postBodyText

And you'll have to change Content-Type to application/x-www-form-urlencoded.

Reference: http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-1#sending_simple_types

For starters, this should work:

public async Task<HttpStatusCode> SendAsync(Data data)
{
    string jsonData = string.Format("={0}", JsonConvert.SerializeObject(data));
    var content = new StringContent(
            jsonData,
            Encoding.UTF8,
            "application/x-www-form-urlencoded");
        HttpResponseMessage response = await _httpClient.PostAsync(_url, content);

        return response.StatusCode;
}

Alternatively, you could receive a complex type instead of a string in your Controller.

[HttpPost]
[ActionName("postdata")]
public async Task<HttpResponseMessage> PostData(Data data)
{
    // do stuff with data: in this case your original client code should work
}

Upvotes: 0

Related Questions