【问题标题】:C# HttpClient.PostAsJsonAsync Failing with Internal Server ErrorC# HttpClient.PostAsJsonAsync 因内部服务器错误而失败
【发布时间】:2021-12-28 00:30:59
【问题描述】:

我正在尝试使用 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 post 方法,并且 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>);
    });
}

我现在完全不知道该尝试什么。任何帮助将不胜感激。

【问题讨论】:

  • 服务器内部错误是指服务器在处理请求时产生的错误。因此,除非您知道服务器错误背后的原因,否则您无法真正在客户端修复任何内容。

标签: c# rest https httpclient postasync


【解决方案1】:

终于明白了。我必须在 HttpClient 对象本身上设置内容类型。在 using 块中添加了这两行,它起作用了!

client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2021-12-23
    • 2018-01-02
    • 2011-06-21
    • 2017-11-19
    相关资源
    最近更新 更多