C# HttpClient.PostAsJsonAsync 因内部服务器错误而失败

C# HttpClient.PostAsJsonAsync Failing with Internal Server Error

我正在尝试使用 HttpClient PostAsJsonAsync 调用 api。但是,我收到 StatusCode 500 Internal Server Error,经过无数小时的研究和各种尝试,我无法弄清楚原因。

这是我的尝试:

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>);
    });
}

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

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

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