.NET HttpClient 请求内容类型
.NET HttpClient Request Content-Type
我不确定,但在我看来,.NET HttpClient 库的默认实现存在缺陷。看起来它在 PostAsJsonAsync 调用中将 Content-Type 请求值设置为 "text/html"。我已尝试重置请求值,但不确定我是否正确执行此操作。任何建议。
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();
}
您应该设置内容类型。使用 Accept,您可以定义您想要的响应。
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Accept request-header 字段可用于指定响应可接受的某些媒体类型。 Accept headers 可用于指示请求具体限于一小组所需的类型,如请求 in-line 图像的情况。
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);
}
}
我不确定,但在我看来,.NET HttpClient 库的默认实现存在缺陷。看起来它在 PostAsJsonAsync 调用中将 Content-Type 请求值设置为 "text/html"。我已尝试重置请求值,但不确定我是否正确执行此操作。任何建议。
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();
}
您应该设置内容类型。使用 Accept,您可以定义您想要的响应。
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html Accept request-header 字段可用于指定响应可接受的某些媒体类型。 Accept headers 可用于指示请求具体限于一小组所需的类型,如请求 in-line 图像的情况。
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);
}
}