簡體   English   中英

C# HttpClient.PostAsJsonAsync 因內部服務器錯誤而失敗

[英]C# HttpClient.PostAsJsonAsync Failing with Internal Server Error

我正在嘗試使用 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 類型的 object。 我還嘗試更改 api 服務器以接受通用 object 無濟於事。 我已經使用 Insomnia 成功調用了這個 api 發布方法,該方法位於與所示代碼相同的服務器上,並且 GetToken() 方法成功地調用了同一 api 中的另一個端點方法,因此它擊中了 Z8A5DA52ED126447D359E70C 並成功驗證。057218AZA

我也嘗試過像這樣使用 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 object 本身上設置內容類型。 在 using 塊中添加了這兩行,它起作用了!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM