如何为HttpClient的GetFromJsonAsync<T>调用全局配置JsonSerializerOptions
为指定HttpClient全局配置Json序列化选项
全局配置所有HttpClient
如果需要让所有通过依赖注入获取的HttpClient都使用统一的Json序列化规则,直接配置HttpJsonOptions即可:
builder.Services.ConfigureHttpJsonOptions(options => { options.SerializerOptions.PropertyNameCaseInsensitive = true; options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
配置完成后,所有GetFromJsonAsync调用无需手动传入JsonSerializerOptions参数,会自动使用全局配置:
await httpClient.GetFromJsonAsync<Item[]>(uri);
为特定命名HttpClient单独配置
如果只需要给某个指定的HttpClient应用配置,注册命名HttpClient时链式调用ConfigureHttpJsonOptions:
// 注册命名HttpClient并配置Json选项 builder.Services.AddHttpClient("MyTargetClient", client => { // 可额外配置HttpClient基础地址、超时等 client.BaseAddress = new Uri("https://your-api-domain.com/"); client.Timeout = TimeSpan.FromSeconds(30); }) .ConfigureHttpJsonOptions(options => { options.SerializerOptions.PropertyNameCaseInsensitive = true; options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()); });
使用时通过IHttpClientFactory获取该命名HttpClient:
private readonly HttpClient _targetClient; public YourService(IHttpClientFactory httpClientFactory) { _targetClient = httpClientFactory.CreateClient("MyTargetClient"); } // 直接调用,无需传序列化参数 var items = await _targetClient.GetFromJsonAsync<Item[]>(uri);
为什么之前的配置未生效
你尝试的Configure<JsonSerializerOptions>和AddJsonOptions是针对ASP.NET Core MVC/Razor Pages的Json序列化配置,并非HttpClient.GetFromJsonAsync所用的配置。只有ConfigureHttpJsonOptions才是专门配置System.Net.Http.Json扩展方法的序列化选项。
内容的提问来源于stack exchange,提问作者Nicolas
相关产品推荐
相关产品推荐

