首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C# HttpClient.PostAsJsonAsync失败与内部服务器错误

C# HttpClient.PostAsJsonAsync失败与内部服务器错误
EN

Stack Overflow用户
提问于 2021-12-28 00:30:59
回答 1查看 760关注 0票数 0

我试图使用HttpClient PostAsJsonAsync调用api。然而,我得到了一个StatusCode 500内部服务器错误,我不知道为什么,经过无数个小时的研究和各种尝试。

以下是我的尝试:

代码语言:javascript
运行
复制
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()的实现:

代码语言:javascript
运行
复制
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,而不是这样:

代码语言:javascript
运行
复制
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>);
    });
}

我现在根本想不出该尝试什么了。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-28 03:36:11

终于弄明白了。我必须在HttpClient对象本身上设置内容类型。在using块中添加了这2行,它就可以工作了!

代码语言:javascript
运行
复制
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70501697

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档