ant-design-blazor/components/core/Extensions/HttpClientExtensions.cs
老九 2d685ebe4b fix: deserialization UTF8 encoding issue in extension method of HttpClient (#717)
* 修复HttpClientExtensions反序列化时没有判断内容是否为utf8编码的问题

(cherry picked from commit f6e4903c9336d0f1a43f1da3fe148e08bb917f3f)

* fix: translation comments

Co-authored-by: ElderJames <shunjiey@hotmail.com>
2020-10-25 18:54:59 +08:00

73 lines
2.4 KiB
C#

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace AntDesign.core.Extensions
{
internal static class HttpClientExtensions
{
public static async Task<TValue> GetFromJsonAsync<TValue>(this HttpClient client, string requestUri, CancellationToken cancellationToken = default)
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}
var res = await client.GetAsync(requestUri, cancellationToken);
if (res.IsSuccessStatusCode)
{
var utf8Json = await res.Content.ReadAsByteArrayAsync(Encoding.UTF8);
return JsonSerializer.Deserialize<TValue>(utf8Json, new JsonSerializerOptions()
{
PropertyNameCaseInsensitive = true,
});
}
return default;
}
/// <summary>
/// Reads as a binary array and converts to the specified encoding
/// </summary>
/// <param name="httpContent"></param>
/// <param name="dstEncoding">The target encoding</param>
/// <exception cref="ArgumentException"></exception>
/// <returns></returns>
private static async Task<byte[]> ReadAsByteArrayAsync(this HttpContent httpContent, Encoding dstEncoding)
{
var encoding = httpContent.GetEncoding();
var byteArray = await httpContent.ReadAsByteArrayAsync().ConfigureAwait(false);
return encoding.Equals(dstEncoding)
? byteArray
: Encoding.Convert(encoding, dstEncoding, byteArray);
}
/// <summary>
/// Get encoding information from <see cref="HttpContent"/>
/// </summary>
/// <param name="httpContent"></param>
/// <returns></returns>
private static Encoding GetEncoding(this HttpContent httpContent)
{
var charSet = httpContent.Headers.ContentType?.CharSet;
if (string.IsNullOrEmpty(charSet) == true)
{
return Encoding.UTF8;
}
var span = charSet.AsSpan().TrimStart('"').TrimEnd('"');
if (span.Equals(Encoding.UTF8.WebName, StringComparison.OrdinalIgnoreCase))
{
return Encoding.UTF8;
}
return Encoding.GetEncoding(span.ToString());
}
}
}