繁体   English   中英

HttpClient.PutAsync-“实体仅允许使用JSON Content-Type标头进行写入”

[英]HttpClient.PutAsync - “Entity only allows writes with a JSON Content-Type header”

我有一个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

并回应:

实体仅允许使用JSON Content-Type标头进行写入

肯定在错误中,我也可以看到:

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();
}

还要注意不要通过将.Result类的阻塞调用与async方法混合使用来正确使用async / await,因为这可能导致死锁。

参考Async / Await-异步编程最佳实践

使用StringContent构造函数设置内容类型:

HttpContent content = new StringContent(JsonConvert.SerializeObject(UnSerializedContent), System.Text.Encoding.UTF8, "application/json");

据我所知,在使用HttpClient时,您并不是要在请求对象上设置内容标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM