简体   繁体   中英

C# HttpClient.PostAsJsonAsync Failing with Internal Server Error

I am trying to call an api using HttpClient PostAsJsonAsync. However, I'm getting a StatusCode 500 Internal Server Error and I cannot figure out why after countless hours of research and various attempts.

Here is my attempt:

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

(Note: I've removed most code after the PostAsJsonAsync call as that's not even being called since the post call is failing)

Here is the implementation of 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;
}

I've verified the GetToken() method and publicApiAuthKey have the correct values. The api server's Post method is expecting an object of the same AppServiceCall type. I've also tried changing the api server to accept a generic object to no avail. I have successfully called this api post method using Insomnia located on the same server as the code shown, and the GetToken() method is successfully calling another endpoint method within that same api, so it is hitting that api and successfully authenticating.

I've also tried using PostAsync instead like this:

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

I'm simply out of ideas of what to even try now. Any help would be greatly appreciated.

Finally figured it out. I had to set the content type on the HttpClient object itself. Added these 2 lines in the using block and it worked!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM