Sending json with .NET HttpClient to WebAPI server

I am trying to send json via POST using HttpClientin my web service.

Submit 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 a WebAPI controller with the 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
    }

jsonParam in this method null. jsonDataIt’s good if I copy and paste it into the request sender (I use Postman), everything will be successful.

It's about how I construct content and use HttpClient, but I can’t understand what happened.

Can anyone see the problem?

+4
source share
2 answers

POST json, System.Net.Http.Formatting "" , StringContent.

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

        return response.StatusCode;
}

.

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

    }

HttpClientExtensions - http://msdn.microsoft.com/en-us/library/hh944521(v=vs.118).aspx

+3

:

=postBodyText

Content-Type application/x-www-form-urlencoded.

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

:

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;
}

.

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

All Articles