gpt4 book ai didi

c# - HttpClient.PutAsync- "Entity only allows writes with a JSON Content-Type header"

转载 作者:行者123 更新时间:2023-11-30 14:47:08 25 4
gpt4 key购买 nike

我有一个可以完美发布数据的POST方法。

查看文档似乎 PATCH(或 PUT)应该看起来完全一样,只需使用 PutAsync 而不是 PostAsync

好吧,我收到以下错误:

+       postResponse    {StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.NoWriteNoSeekStreamContent, Headers:
{
Cache-Control: private
Date: Mon, 09 Oct 2017 12:19:28 GMT
Transfer-Encoding: chunked
request-id: 60370069-f7c4-421d-842e-b1ee8573c2c2
client-request-id: 60370069-f7c4-421d-842e-b1ee8573c2c2
x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"North Europe","Slice":"SliceB","ScaleUnit":"002","Host":"AGSFE_IN_7","ADSiteName":"DUB"}}
Duration: 3.2626
Content-Type: application/json
}} System.Net.Http.HttpResponseMessage

和响应:

Entity only allows writes with a JSON Content-Type header

果然在错误中我也可以看到这个:

ContentType {text/plain; charset=utf-8} System.Net.Http.Headers.MediaTypeHeaderValue

所以错误是有道理的,但是,我确实告诉它使用 JSON,并且它在我的 POST 方法中使用相同的代码按预期工作:

public async Task UpdateToGraph(object UnSerializedContent, string relativeUrl)
{
string accessToken = await _tokenManager.GetAccessTokenAsync();
HttpContent content = new StringContent(JsonConvert.SerializeObject(UnSerializedContent));

Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Client.DefaultRequestHeaders.Add("ContentType", "application/json");

string endpoint = "https://graph.microsoft.com/v1.0" + relativeUrl;
var postResponse = Client.PutAsync(endpoint, content).Result;

string serverResponse = postResponse.Content.ReadAsStringAsync().Result;
}

最佳答案

您可以使用 .{Verb}AsJsonAsync HttpClientExtensions方法。

public async Task UpdateToGraph(object UnSerializedContent, string relativeUrl) {
var accessToken = await _tokenManager.GetAccessTokenAsync();

Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
Client.DefaultRequestHeaders.Add("ContentType", "application/json");

var endpoint = "https://graph.microsoft.com/v1.0" + relativeUrl;
var postResponse = await Client.PutAsJsonAsync(endpoint, UnSerializedContent);

var serverResponse = await postResponse.Content.ReadAsStringAsync();
}

另请注意正确使用 async/await,不要将 .Result 等阻塞调用与 async 方法混合使用,因为这会导致死锁。

引用 Async/Await - Best Practices in Asynchronous Programming

关于c# - HttpClient.PutAsync- "Entity only allows writes with a JSON Content-Type header",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46646434/

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