Методы расширения сериализации в HttpClient
Сериализация и десериализация полезных данных JSON из сети являются общими операциями. Методы расширения для HttpClient и HttpContent позволяют выполнять эти операции в одной строке кода. Эти методы расширения используют веб-значения по умолчанию для JsonSerializerOptions.
В следующем примере показано использование HttpClientJsonExtensions.GetFromJsonAsync и HttpClientJsonExtensions.PostAsJsonAsync:
using System.Net.Http.Json;
namespace HttpClientExtensionMethods
{
public class User
{
public int Id { get; set; }
public string? Name { get; set; }
public string? Username { get; set; }
public string? Email { get; set; }
}
public class Program
{
public static async Task Main()
{
using HttpClient client = new()
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com")
};
// Get the user information.
User? user = await client.GetFromJsonAsync<User>("users/1");
Console.WriteLine($"Id: {user?.Id}");
Console.WriteLine($"Name: {user?.Name}");
Console.WriteLine($"Username: {user?.Username}");
Console.WriteLine($"Email: {user?.Email}");
// Post a new user.
HttpResponseMessage response = await client.PostAsJsonAsync("users", user);
Console.WriteLine(
$"{(response.IsSuccessStatusCode ? "Success" : "Error")} - {response.StatusCode}");
}
}
}
// Produces output like the following example but with different names:
//
//Id: 1
//Name: Tyler King
//Username: Tyler
//Email: Tyler@contoso.com
//Success - Created
Imports System.Net.Http
Imports System.Net.Http.Json
Namespace HttpClientExtensionMethods
Public Class User
Public Property Id As Integer
Public Property Name As String
Public Property Username As String
Public Property Email As String
End Class
Public Class Program
Public Shared Async Function Main() As Task
Using client As New HttpClient With {
.BaseAddress = New Uri("https://jsonplaceholder.typicode.com")
}
' Get the user information.
Dim user1 As User = Await client.GetFromJsonAsync(Of User)("users/1")
Console.WriteLine($"Id: {user1.Id}")
Console.WriteLine($"Name: {user1.Name}")
Console.WriteLine($"Username: {user1.Username}")
Console.WriteLine($"Email: {user1.Email}")
' Post a new user.
Dim response As HttpResponseMessage = Await client.PostAsJsonAsync("users", user1)
Console.WriteLine(
$"{(If(response.IsSuccessStatusCode, "Success", "Error"))} - {response.StatusCode}")
End Using
End Function
End Class
End Namespace
' Produces output like the following example but with different names:
'
'Id: 1
'Name: Tyler King
'Username: Tyler
'Email: Tyler@contoso.com
'Success - Created
Совместная работа с нами на GitHub
Источник этого содержимого можно найти на GitHub, где также можно создавать и просматривать проблемы и запросы на вытягивание. Дополнительные сведения см. в нашем руководстве для участников.