HttpClient.PutAsync - “实体只允许使用JSON Content-Type标题进行写入”
问题描述:
我有一个可以完美发布数据的POST方法。HttpClient.PutAsync - “实体只允许使用JSON Content-Type标题进行写入”
看看文档看起来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方法中使用相同的cod E:
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
方法,因为这可能会导致死锁等待。
答
使用的StringContent构造函数中设置内容类型:
HttpContent content = new StringContent(JsonConvert.SerializeObject(UnSerializedContent), System.Text.Encoding.UTF8, "application/json");
据我所知,你是不是要设置内容头请求对象上使用时, HttpClient的。
谢谢'HttpClient的不包含PutAsJsonAsync'的定义,认为我失去了一些东西? :) –
@Green_qaue你可能缺少一个参考https://msdn.microsoft.com/en-us/library/system.net.http.httpclientextensions.putasjsonasync(v=vs.118).aspx – Nkosi
找到它,谢谢:)另一个问题是,如果我删除'.Result',我不能再访问'postResponse.Content' –