使用 System.Net.Http.Json 简化 HttpClient 的使用
使用 System.Net.Http.Json 簡化 HttpClient 的使用
Intro
從 .NET Core 3.1 開始,微軟添加了一個 System.Net.Http.Json 的擴展,可以用來簡化 HttpClient 的使用,看到在很多項目里還并未開始使用,所以想向大家介紹一下
Sample
PostAsJson/PutAsJson
PostAsJson sample:
const?string?url?=?"http://localhost:5000/api/values"; using?var?httpClient?=?new?HttpClient();using?var?response?=?await?httpClient.PostAsJsonAsync(url,?new?Category() {Id?=?1,Name?=?"Test" }); response.EnsureSuccessStatusCode();PutAsJson:
using?var?response?=?await?httpClient.PutAsJsonAsync(url,?new?Category() {Id?=?1,Name?=?"Test" }); response.EnsureSuccessStatusCode();簡單來說就是會把一個對象變成 JSON request body
目前支持 Post 和 Put 方法 默認的序列化方式和 ASP.NET Core 是一致的,會變成 camalCase, 例如
如果要自定義序列化,可以傳入一個 JsonSerializerOptions,如:
using?var?response?=?await?httpClient.PostAsJsonAsync(url,?new?Category() {Id?=?1,Name?=?"Test" },?new?JsonSerializerOptions()); response.EnsureSuccessStatusCode();可以看到這個例子中的 body 和之前有所不同了,這正是因為我們使用了自定義的 JsonSerializerOptions
GetFromJsonAsync
var?result?=?await?httpClient.GetFromJsonAsync<ResultModel>(url); ArgumentNullException.ThrowIfNull(result); Console.WriteLine($"{result.Status}:?{result.ErrorMsg}");和上面的 AsJson 相對應,這個是從 Response body 到一個對象,同樣地也支持自定義 JsonSerializerOptions,可以自己嘗試一下
ReadFromJsonAsync
using?var?response?=?await?httpClient.PutAsJsonAsync(url,?new?Category() {Id?=?1,Name?=?"Test" }); response.EnsureSuccessStatusCode(); var?result?=?await?response.Content.ReadFromJsonAsync<ResultModel>(); ArgumentNullException.ThrowIfNull(result); Console.WriteLine($"{result.Status}:?{result.ErrorMsg}");直接從 HttpContent 中讀取 json 對象
JsonContent.Create
using?var?content?=?JsonContent.Create(new?Category()?{?Id?=?1,?Name?=?"Test"?}); using?var?response?=?await?httpClient.PostAsync(url,?content); response.EnsureSuccessStatusCode();從一個對象構建 HttpContent ,同樣支持自定義序列化
MoreSample
使用前后的一些對比:
More
JSON現在已經非常的普遍了,這一擴展可以使得 HttpClient 處理 JSON 更為簡單,而且從 .NET 6 開始已經包含在了框架中,不需要再手動引用 nuget 包了
在 .NET 7 中會增加一個 PatchAsJsonAsync 的擴展方法,目前發布的 Preview 1 已經可用,使用方法類似于 PostAsJsonAsync/PutAsJsonAsync,HttpMethod 是 Patch
另外覺得應該有一個類似于 GetFromJsonAsync 的 DeleteFromJsonAsync,提了一個 issue,感興趣的可以關注一下:https://github.com/dotnet/runtime/issues/65617
如果返回的 response 狀態碼不是 2xx,GetFromJsonAsync 會拋異常,如果是不合法的 JSON 也會拋出異常
References
https://github.com/dotnet/runtime/issues/65617
https://github.com/dotnet/runtime/tree/main/src/libraries/System.Net.Http.Json/src/System/Net/Http/Json
https://github.com/WeihanLi/SamplesInPractice/blob/master/HttpClientTest/JsonExtensionSample.cs
https://github.com/OpenReservation/ReservationServer/commit/d07f9dc5ae292dd748d7f7a879898009c198d70d
總結
以上是生活随笔為你收集整理的使用 System.Net.Http.Json 简化 HttpClient 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ABP vNext微服务架构详细教程——
- 下一篇: .NET6之MiniAPI(十八):Op