gpt4 book ai didi

c# - .NET HttpClient 请求内容类型

转载 作者:太空狗 更新时间:2023-10-29 21:32:51 25 4
gpt4 key购买 nike

我不确定,但在我看来,.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.htmlAccept 请求 header 字段可用于指定响应可接受的某些媒体类型。 Accept 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);
}
}

关于c# - .NET HttpClient 请求内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com