.NET HttpClient请求内容类型

时间:2016-01-04 20:11:36

标签: c# .net json asp.net-web-api2

我不确定,但在我看来,.NET HttpClient库的默认实现存在缺陷。看起来它将Content-Type请求值设置为" text / html"在PostAsJsonAsync调用上。我尝试重置请求值,但不确定我是否正确执行此操作。任何建议。

public async Task<string> SendPost(Model model)
{
    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.PostAsJsonAsync(Url + "api/foo/", model);
    response.EnsureSuccessStatusCode();
    return await response.Content.ReadAsStringAsync();    
}

1 个答案:

答案 0 :(得分:6)

您应该设置内容类型。使用“接受”,您可以定义所需的响应。

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Accept request-header字段可用于指定响应可接受的某些媒体类型。接受标头可用于指示请求特别限于一小组所需类型,如在请求内嵌图像的情况下。

public async Task<string> SendPost(Model model)
{
    var client = new HttpClient(); //You should extract this and reuse the same instance multiple times.
    var request = new HttpRequestMessage(HttpMethod.Post, Url + "api/foo");
    using(var content = new StringContent(Serialize(model), Encoding.UTF8, "application/json"))
    {
        request.Content = content;
        var response = await client.SendAsync(request).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    }
}
相关问题