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

时间:2017-10-09 12:26:38

标签: c# asp.net-mvc http-headers dotnet-httpclient

我有一个可以完美发布数据的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;
}

2 个答案:

答案 0 :(得分:4)

您可以使用.{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

答案 1 :(得分:1)

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

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

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