Asp.net

如何從 HttpClient.PostAsJsonAsync() 生成的 Content-Type 標頭中刪除 charset=utf8?

  • March 9, 2022

我對 HttpClient.PostAsJsonAsync() 有疑問

除了“Content-Type”標頭中的“application/json”之外,該方法還添加了“charset=utf-8”

所以標題看起來像這樣:

內容類型:應用程序/json;字元集=utf-8

雖然 ASP.NET WebAPI 對此標頭沒有任何問題,但我發現我作為客戶端使用的其他 WebAPI 不接受帶有此標頭的請求,除非它只是 application/json。

無論如何在使用 PostAsJsonAsync() 時從 Content-Type 中刪除“charset=utf-8”,還是應該使用其他方法?

解決方案: 感謝 Yishai!

using System.Net.Http.Headers;

public class NoCharSetJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
  public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
  {
      base.SetDefaultContentHeaders(type, headers, mediaType);
      headers.ContentType.CharSet = "";
  }
}

public static class HttpClientExtensions
{
   public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
   {
       return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter(), cancellationToken);
   }

   public static async Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value)
   {
       return await client.PostAsync(requestUri, value, new NoCharSetJsonMediaTypeFormatter());
   }
}

您可以從 JsonMediaTypeFormatter 派生並覆蓋 SetDefaultContentHeaders。

打電話base.SetDefaultContentHeaders()然後清除headers.ContentType.CharSet

然後根據以下程式碼編寫自己的擴展方法:

public static Task<HttpResponseMessage> PostAsJsonAsync<T>(this HttpClient client, string requestUri, T value, CancellationToken cancellationToken)
{
   return client.PostAsync(requestUri, value, 
           new JsonMediaTypeFormatter(), cancellationToken);
}

本質上是這樣的:

public static Task<HttpResponseMessage> PostAsJsonWithNoCharSetAsync<T>(this HttpClient client, string requestUri, T value, CancellatioNToken cancellationToken)
{
   return client.PostAsync(requestUri, value, 
         new NoCharSetJsonMediaTypeFormatter(), cancellationToken);
}

引用自:https://stackoverflow.com/questions/23161088