Skip to content

Commit 567f8d7

Browse files
committed
使用System.Net.Http.Json处理json
1 parent 6e22226 commit 567f8d7

File tree

7 files changed

+25
-124
lines changed

7 files changed

+25
-124
lines changed

WebApiClientCore.Abstractions/HttpApiRequestMessage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,10 @@ public abstract class HttpApiRequestMessage : HttpRequestMessage
3434
/// <param name="name">名称</param>
3535
/// <param name="value">值</param>
3636
/// <returns></returns>
37-
public async Task AddFormFieldAsync(string name, string? value)
37+
public Task AddFormFieldAsync(string name, string? value)
3838
{
3939
var keyValue = new KeyValue(name, value);
40-
await this.AddFormFieldAsync(Enumerable.Repeat(keyValue, 1)).ConfigureAwait(false);
40+
return this.AddFormFieldAsync(Enumerable.Repeat(keyValue, 1));
4141
}
4242

4343
/// <summary>

WebApiClientCore.Benchmarks/Others/ReadAsJsonBenchamrk.cs

Lines changed: 0 additions & 36 deletions
This file was deleted.

WebApiClientCore.Extensions.OAuths/TokenProviders/OAuth2TokenClient.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.ComponentModel.DataAnnotations;
44
using System.Diagnostics.CodeAnalysis;
55
using System.Net.Http;
6+
using System.Net.Http.Json;
67
using System.Threading.Tasks;
78
using WebApiClientCore.Attributes;
89
using WebApiClientCore.HttpContents;
@@ -90,7 +91,7 @@ public OAuth2TokenClient(IHttpClientFactory httpClientFactory, IOptionsMonitor<H
9091
formContent.AddFormField(new KeyValue("grant_type", grant_type));
9192

9293
var response = await this.httpClientFactory.CreateClient().PostAsync(endpoint, formContent);
93-
return await response.Content.ReadAsJsonAsync<TokenResult>(this.httpApiOptions.JsonDeserializeOptions);
94+
return await response.Content.ReadFromJsonAsync<TokenResult>(this.httpApiOptions.JsonDeserializeOptions);
9495
}
9596
}
9697
}

WebApiClientCore/ApiResponseContextExtensions.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using System;
22
using System.Diagnostics.CodeAnalysis;
3-
using System.Net.Http;
3+
using System.Net.Http.Json;
44
using System.Threading.Tasks;
55
using WebApiClientCore.Serialization;
66

@@ -29,7 +29,7 @@ public static class ApiResponseContextExtensions
2929

3030
var content = response.Content;
3131
var options = context.HttpContext.HttpApiOptions.JsonDeserializeOptions;
32-
return await content.ReadAsJsonAsync(objType, options, context.RequestAborted);
32+
return await content.ReadFromJsonAsync(objType, options, context.RequestAborted);
3333
}
3434

3535
/// <summary>
Lines changed: 12 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
using System;
22
using System.Diagnostics.CodeAnalysis;
33
using System.Net.Http.Headers;
4+
using System.Net.Http.Json;
45
using System.Text;
56
using System.Threading.Tasks;
6-
using WebApiClientCore.HttpContents;
77

88
namespace WebApiClientCore.Attributes
99
{
@@ -13,9 +13,10 @@ namespace WebApiClientCore.Attributes
1313
/// </summary>
1414
public class JsonContentAttribute : HttpContentAttribute, ICharSetable
1515
{
16-
/// <summary>
17-
/// 编码方式
18-
/// </summary>
16+
private const string jsonMediaType = "application/json";
17+
private static readonly MediaTypeHeaderValue defaultMediaType = new(jsonMediaType);
18+
19+
private MediaTypeHeaderValue mediaType = defaultMediaType;
1920
private Encoding encoding = Encoding.UTF8;
2021

2122
/// <summary>
@@ -25,7 +26,11 @@ public class JsonContentAttribute : HttpContentAttribute, ICharSetable
2526
public string CharSet
2627
{
2728
get => this.encoding.WebName;
28-
set => this.encoding = Encoding.GetEncoding(value);
29+
set
30+
{
31+
this.encoding = Encoding.GetEncoding(value);
32+
this.mediaType = new MediaTypeHeaderValue(jsonMediaType) { CharSet = this.encoding.WebName };
33+
}
2934
}
3035

3136
/// <summary>
@@ -36,30 +41,12 @@ public string CharSet
3641
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
3742
[UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
3843
protected override Task SetHttpContentAsync(ApiParameterContext context)
39-
{
40-
context.HttpContext.RequestMessage.Content = this.CreateContent(context);
41-
return Task.CompletedTask;
42-
}
43-
44-
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
45-
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
46-
#if NET5_0_OR_GREATER
47-
private System.Net.Http.Json.JsonContent CreateContent(ApiParameterContext context)
4844
{
4945
var value = context.ParameterValue;
50-
var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions;
5146
var valueType = value == null ? context.Parameter.ParameterType : value.GetType();
52-
var mediaType = Encoding.UTF8.Equals(this.encoding) ? defaultMediaType : new MediaTypeHeaderValue(JsonContent.MediaType) { CharSet = this.CharSet };
53-
return System.Net.Http.Json.JsonContent.Create(value, valueType, mediaType, options);
54-
}
55-
private static readonly MediaTypeHeaderValue defaultMediaType = new(JsonContent.MediaType);
56-
#else
57-
private JsonContent CreateContent(ApiParameterContext context)
58-
{
59-
var value = context.ParameterValue;
6047
var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions;
61-
return new JsonContent(value, options, this.encoding);
48+
context.HttpContext.RequestMessage.Content = JsonContent.Create(value, valueType, this.mediaType, options);
49+
return Task.CompletedTask;
6250
}
63-
#endif
6451
}
6552
}

WebApiClientCore/System.Net.Http/HttpContentExtensions.cs

Lines changed: 3 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
using System.Diagnostics.CodeAnalysis;
2-
using System.Reflection;
1+
using System.Reflection;
32
using System.Runtime.CompilerServices;
43
using System.Text;
5-
using System.Text.Json;
64
using System.Threading;
75
using System.Threading.Tasks;
86
using WebApiClientCore;
@@ -72,61 +70,8 @@ public static void EnsureNotBuffered(this HttpContent httpContent)
7270
{
7371
throw new HttpContentBufferedException();
7472
}
75-
}
76-
77-
78-
/// <summary>
79-
/// 读取 json 内容为指定的类型
80-
/// </summary>
81-
/// <typeparam name="T">目标类型</typeparam>
82-
/// <param name="content">http内容</param>
83-
/// <param name="options">json反序列化选项</param>
84-
/// <param name="cancellationToken">取消令牌</param>
85-
/// <returns></returns>
86-
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
87-
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
88-
public static async Task<T?> ReadAsJsonAsync<T>(this HttpContent content, JsonSerializerOptions? options, CancellationToken cancellationToken = default)
89-
{
90-
var srcEncoding = content.GetEncoding();
91-
if (Encoding.UTF8.Equals(srcEncoding))
92-
{
93-
using var utf8Json = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
94-
return await JsonSerializer.DeserializeAsync<T>(utf8Json, options, cancellationToken).ConfigureAwait(false);
95-
}
96-
else
97-
{
98-
var byteArray = await content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
99-
var utf8Json = Encoding.Convert(srcEncoding, Encoding.UTF8, byteArray);
100-
return JsonSerializer.Deserialize<T>(utf8Json, options);
101-
}
102-
}
103-
104-
/// <summary>
105-
/// 读取 json 内容为指定的类型
106-
/// </summary>
107-
/// <param name="content">http内容</param>
108-
/// <param name="objType">目标类型</param>
109-
/// <param name="options">json反序列化选项</param>
110-
/// <param name="cancellationToken">取消令牌</param>
111-
/// <returns></returns>
112-
[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
113-
[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
114-
public static async Task<object?> ReadAsJsonAsync(this HttpContent content, Type objType, JsonSerializerOptions? options, CancellationToken cancellationToken = default)
115-
{
116-
var srcEncoding = content.GetEncoding();
117-
if (Encoding.UTF8.Equals(srcEncoding))
118-
{
119-
using var utf8Json = await content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
120-
return await JsonSerializer.DeserializeAsync(utf8Json, objType, options, cancellationToken).ConfigureAwait(false);
121-
}
122-
else
123-
{
124-
var byteArray = await content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false);
125-
var utf8Json = Encoding.Convert(srcEncoding, Encoding.UTF8, byteArray);
126-
return JsonSerializer.Deserialize(utf8Json, objType, options);
127-
}
128-
}
129-
73+
}
74+
13075
/// <summary>
13176
/// 读取为二进制数组并转换为 utf8 编码
13277
/// </summary>

WebApiClientCore/WebApiClientCore.csproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@
1919
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="3.0.0" />
2020
</ItemGroup>
2121

22+
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.1'">
23+
<PackageReference Include="System.Net.Http.Json" Version="3.2.0" />
24+
</ItemGroup>
25+
2226
<ItemGroup>
2327
<ProjectReference Include="..\WebApiClientCore.Abstractions\WebApiClientCore.Abstractions.csproj" />
2428
<ProjectReference Include="..\WebApiClientCore.Analyzers\WebApiClientCore.Analyzers.csproj" ReferenceOutputAssembly="false" />

0 commit comments

Comments
 (0)