Gre*_*aue 7 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
Run Code Online (Sandbox Code Playgroud)
和回应:
实体仅允许使用 JSON Content-Type 标头写入
果然在错误中我也可以看到:
ContentType {text/plain; charset=utf-8} System.Net.Http.Headers.MediaTypeHeaderValue
Run Code Online (Sandbox Code Playgroud)
所以这个错误是有道理的,但是,我确实告诉它使用 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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用.{Verb}AsJsonAsyncHttpClientExtensions方法。
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();
}
Run Code Online (Sandbox Code Playgroud)
另请注意 async/await 的正确使用,不要将阻塞调用.Result与async方法混合使用,因为这可能会导致死锁。
| 归档时间: |
|
| 查看次数: |
4390 次 |
| 最近记录: |