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

标签 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

和响应:

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/

相关文章:

c# - Appium 找不到 2/3 seekbar 的 ID 但都在同一页面上

asp.net-mvc - 如何将 ASP.Net MVC 路由段中的 1 或 0 映射到 bool 操作方法输入参数

java - 使用 AWS Java SDK 为现有 S3 对象设置过期 header

c# - 反序列化 JSON 对象与数组

c# - xmlreader,获取属性的名称

c# - 调试符号未加载到针对 .NET Framework 的 .NET 标准项目中

c# - Ninject 的 UnitOfWork 模式应该使用什么选项

c# - Monorail 无法读取从 jQuery 接收到的 JSON(对象列表)数据

带有 POST 或 PUT 的 jQuery.ajax 没有 IE8 和 IE9 的响应 header

http - 允许任何 CORS 源 (*) 时是否应设置 'Vary: Origin'?