簡體   English   中英

HttpClient.SendAsync 發送錯誤的 Content-Type

[英]HttpClient.SendAsync sending wrong Content-Type

        HttpClient httpClient = new HttpClient();
        MyRequest request = new MyRequest (data);

        var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(request), System.Text.Encoding.UTF8, "application/json");

        HttpRequestMessage httpRequestMessage = new HttpRequestMessage
        {
            RequestUri = new Uri("http://localhost:8000/api/action"),
            Content = content,
            Method = HttpMethod.Post          
        };
      
        httpRequestMessage.SetBrowserRequestMode(BrowserRequestMode.NoCors);
            
        await httpClient.SendAsync(httpRequestMessage);

在 Blazor WebAssembly 中使用 HttpClient 我正在嘗試向 API 發送請求。

但是,盡管將application/json指定為內容類型,但它會發送text/plain;charset=UTF-8 (在 Chrome 網絡選項卡中查看)。 這會導致 API 引發錯誤。

我想你可以檢查這些案例: case1case2閱讀此文檔,並嘗試使用 PostAsJsonAsync 方法

我測試如下並且運行良好:

var weatherforecast = new WeatherForecast() { Date = DateTime.Now, Summary = "testsummary", TemperatureC = 44 };           
var response = await Http.PostAsJsonAsync("https://localhost:44385/WeatherForecast", weatherforecast);

結果: 在此處輸入圖像描述

相關帖子: 錯誤的 Content-Type 被替換為 fetch http 請求

WebAssembly 中的 HttpClient 調用標准的 fetch 方法。

根據使用 no-cors 時的提取規范,只能使用有限數量的內容類型: https ://fetch.spec.whatwg.org/#simple-header

  • “應用程序/x-www-form-urlencoded”
  • “多部分/表單數據”
  • “文本/純文本”

首選的解決方案是正確配置您調用的端點以允許跨源請求而不是使用 no-cors 例如: https ://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ 訪問控制允許來源訪問控制允許來源:*

如果這是不可能的(在我的情況下)並且您必須使用 no-cors 唯一的其他選擇是將您的端點更改為將“text/plain”映射到“application/json”

雖然許多人可能不認為這是一個錯誤,但它是 HttpClient 行為方式的不一致並且不明顯(盡管 NoCors 選項僅在 WebAssembly 中可用)

暫無
暫無

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

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