天天看點

HttpClient來自官方的JSON擴充方法

System.Net.Http.Json

Json的序列化和反序列化是我們日常常見的操作,通過System.Net.Http.Json我們可以用少量的代碼實作上述操作.正如在github設計文檔中所描述

Serializing and deserializing JSON payloads from the network is a very
common operation for clients, especially in the upcoming Blazor
environment. Right now, sending a JSON payload to the server requires
multiple lines of code, which will be a major speed bump for those
customers. We'd like to add extension methods on top of HttpClient that
allows doing those operations with a single method call.      

他的依賴項也非常的少目前隻依賴System.Net.Http, System.Text.Json

System.Text.Json相對于Newtonsoftjson平均快了兩倍,如果有興趣相關基準測試可在這個文章中查閱

https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

在.NET中安裝和使用

目前它還是預覽版本

dotnet add package System.Net.Http.Json      
public static async TaskGetCustomerAsync()
{
    HttpClient clinet=new HttpClient();
    var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:5000/customers");
    var response = await clinet.SendAsync(request);
    return await response.Content.ReadFromJsonAsync();
}      
public static async TaskCreateCustomerAsync()
{
    HttpClient clinet = new HttpClient();
    var customer=new Customer()
    {
        Id = "1",
        Name = "Fh"
    };
    var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost:5000/create");
    request.Content = JsonContent.Create(customer);
    var response = await clinet.SendAsync(request);
    var content=response.Content.ReadAsStringAsync();
    return customer;
}      
_client.GetFromJsonAsync<IReadOnlyList>("/customers");
_client.GetFromJsonAsync($"/customers/{id}");
_client.PutAsJsonAsync($"/customers/{customerId}", customer);      
if (response.IsSuccessStatusCode)
{
    try
    {
        return await response.Content.ReadFromJsonAsync();
    }
    catch (NotSupportedException) // When content type is not valid
    {
        Console.WriteLine("The content type is not supported.");
    }
    catch (JsonException) // Invalid JSON
    {
        Console.WriteLine("Invalid JSON.");
    }
}