我试图使用HttpClient PostAsJsonAsync调用api。然而,我得到了一个StatusCode 500内部服务器错误,我不知道为什么,经过无数个小时的研究和各种尝试。
以下是我的尝试:
public async Task<T> Test<T>(AppServiceCall call) where T : new()
{
return await Task.Run(() =>
{
async Task<K> PostCall<K>() where K : T, new()
{
K result = new K();
var url = $"/api/{call.Method}";
using (var client = CreateClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetToken());
client.DefaultRequestHeaders.Add("auth-key", publicApiAuthKey);
var response = await client.PostAsJsonAsync(url, call);
}
return result;
}
return WindowsIdentity.RunImpersonated(this.userIdentity.AccessToken, PostCall<T>);
});
}
(注意:在PostAsJsonAsync调用之后,我删除了大部分代码,因为这甚至没有被调用,因为post调用失败了)
下面是CreateClient()的实现:
private HttpClient CreateClient()
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 | SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var client = new HttpClient(new ClientCompressionHandler(new HttpClientHandler { UseDefaultCredentials = true }, new GZipCompressor(), new DeflateCompressor()))
{
BaseAddress = this.baseUri
};
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("defalte"));
return client;
}
我已经验证了GetToken()方法和publicApiAuthKey有正确的值。api服务器的Post方法需要一个相同AppServiceCall类型的对象。我还尝试将api服务器更改为接受泛型对象,但没有效果。我已经使用位于同一服务器上的Insomnia成功地调用了这个api方法,并且GetToken()方法成功地调用了该api中的另一个端点方法,因此它正在命中该api并成功地进行身份验证。
我也尝试过使用PostAsync,而不是这样:
public async Task<T> Test<T>(AppServiceCall call) where T : new()
{
return await Task.Run(() =>
{
async Task<K> PostCall<K>() where K : T, new()
{
K result = new K();
var url = $"/api/{call.Method}";
var wrappedData = new AuthorizationWrapper<AppServiceCall> { Action = call, UserName = this.userIdentity.Name };
var requestJson = JsonConvert.SerializeObject(wrappedData);
var requestContent = new StringContent(requestJson);
using (var client = CreateClient())
{
requestContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", GetToken());
client.DefaultRequestHeaders.Add("auth-key", publicApiAuthKey);
var response = await client.PostAsync(url, requestContent);
}
return result;
}
return WindowsIdentity.RunImpersonated(this.userIdentity.AccessToken, PostCall<T>);
});
}
我现在根本想不出该尝试什么了。任何帮助都将不胜感激。
发布于 2021-12-28 03:36:11
终于弄明白了。我必须在HttpClient对象本身上设置内容类型。在using块中添加了这2行,它就可以工作了!
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
https://stackoverflow.com/questions/70501697
复制相似问题