在我的 ASP.NET Web API 中,我有
httpClient
,它调用 GetFromJsonAsync
:
var jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
jsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
await httpClient.GetFromJsonAsync<Item[]>(uri, jsonSerializerOptions);
在我的所有 GetFromJsonAsync 调用中添加 jsonSerializerOptions 参数是相当重复的,即使我注入它也是如此。
// I tried this without success
builder.Services
.ConfigureHttpJsonOptions(x => x.SerializerOptions.Converters.Add(new JsonStringEnumConverter()))
.Configure<JsonSerializerOptions>(x => x.Converters.Add(new JsonStringEnumConverter()))
.AddJsonOptions(x => x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
// no need to specify the jsonSerializerOptions because it should be configured for this httpClient
await httpClient.GetFromJsonAsync<Item[]>(uri);
有没有办法一次性为每个 httpClient 配置它?
你可以尝试为httpclient创建一个扩展类,然后所有的httpclient都会应用这个选项。
public static class HttpClientExtensions
{
public static JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
public static async Task<T> GetFromJsonAsync<T>(this HttpClient httpClient, string requestUri)
{
var response = await httpClient.GetStringAsync(requestUri);
return JsonSerializer.Deserialize<T>(response, _jsonSerializerOptions);
}
}