使用.NET HttpClient将JSON发送到WebAPI服务器

5

我正在尝试使用HttpClient通过POST向我的Web服务发送JSON。

发送方法非常简单:

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控制器,其中包含以下方法:

    [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复制粘贴到请求发送器(我使用Postman)中,一切都成功了。这与我构建内容和使用 HttpClient 相关,但我无法弄清楚问题出在哪里。有人能看出问题在哪吗?
2个回答

4

由于您试图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/zh-cn/library/hh944521(v=vs.118).aspx


0

当发布单个简单类型时,您需要在发布正文中使用特殊语法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接