发送JSON与.NET的HttpClient到的WebAPI服务器 [英] Sending json with .NET HttpClient to a WebAPI server

查看:624
本文介绍了发送JSON与.NET的HttpClient到的WebAPI服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用的HttpClient 来我的web服务通过POST发送json的。

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

在服务器端,我有以下方法的WebAPI控制器:

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
    }

在jsonParam在这个方法中。该 jsonData 是好的,如果我复制并粘贴到一个请求发送方(我用的邮差)一切顺利。

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.

这是关于我如何构建内容,并使用的HttpClient ,但我无法弄清楚什么是错的。

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?

推荐答案

由于您尝试后JSON,你可以添加一个参考System.Net.Http.Formatting和后期的数据,直接而不需要序列化和创建的StringContent。

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)
    {

    }

在这些HttpClientExtensions方法的更多信息可以在这里找到 - 的 http://msdn.microsoft.com/en-us/library/hh944521(V = vs.118)的.aspx

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

这篇关于发送JSON与.NET的HttpClient到的WebAPI服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆