Metody rozšíření serializace v HttpClient
Serializace a deserializace datových částí JSON ze sítě jsou běžné operace. Metody rozšíření na HttpClient a HttpContent umožňují provádět tyto operace v jednom řádku kódu. Tyto metody rozšíření používají výchozí webu pro JsonSerializerOptions.
Následující příklad ukazuje použití HttpClientJsonExtensions.GetFromJsonAsync a 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
Spolupracujte s námi na GitHubu
Zdroj tohoto obsahu najdete na GitHubu, kde můžete také vytvářet a kontrolovat problémy a žádosti o přijetí změn. Další informace najdete v našem průvodci pro přispěvatele.