gpt4 book ai didi

c# - 如何为 HttpClient (WinForms) 设置默认的 json 序列化设置

转载 作者:行者123 更新时间:2023-11-30 23:05:03 26 4
gpt4 key购买 nike

我有一个使用 Web API 后端的 WinForms 应用程序,我希望所有 HTTP 请求/响应都使用特定的 json SerializerSettings。在服务器端,只需在 Global.asax.cs 中执行此操作即可轻松实现:

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateParseHandling = DateParseHandling.None;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

在客户端,我试过这个:

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateParseHandling = DateParseHandling.None
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);

这在我明确使用 JsonConvert 时有效,例如:

var someVm = JsonConvert.DeserializeObject<SomeVm>(jsonString);

但是对于使用HttpClient.GetAsync/PostAsAsync等调用不生效导致异常:

Error converting value 2/24/2018 4:00:00 PM to type 'System.Nullable1[NodaTime.LocalDateTime]'. Path
'folderExpectedDate', line 16, position 45.
Newtonsoft.Json.JsonSerializationException: Error converting value
2/24/2018 4:00:00 PM to type
'System.Nullable
1[NodaTime.LocalDateTime]'. Path 'folderExpectedDate', line 16, position 45. ---> System.ArgumentException: Could not cast or convert from System.DateTime to NodaTime.LocalDateTime.

请注意,在调用 DeserializeObject 时,导致上述异常的完全相同的 JSON 工作正常。

如何设置/修改 HttpClient 使用的默认序列化设置(我不想在每次调用中都指定它 - 有数百个)?

最佳答案

这是我想出的,到目前为止(为了我的目的)似乎运行良好并且非常干净。

从服务器读取 Json 响应(基于:http://nodogmablog.bryanhogan.net/2017/10/httpcontent-readasasync-with-net-core-2/):

public static class HttpContentExtensions
{
public static async Task<T> ReadAsJsonAsync<T>(this HttpContent content, JsonSerializerSettings jsonSerializerSettings = null)
{
if (jsonSerializerSettings == null)
{
jsonSerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateParseHandling = DateParseHandling.None
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
}

string json = await content.ReadAsStringAsync();
T value = JsonConvert.DeserializeObject<T>(json, jsonSerializerSettings);
return value;
}
}

用法:

var someVm = await response.Content.ReadAsJsonAsync<SomeVm>().ConfigureAwait(false);    

对于 Put、帖子等:

//var response = await WebServiceUtil.HttpClient.PostAsJsonAsync("designSalesJob/new", designSalesJob).ConfigureAwait(false);
var response = await WebServiceUtil.HttpClient.PostAsync("designSalesJob/new", designSalesJob, HttpUtil.JsonFormatter).ConfigureAwait(false);

这是 JsonFormatter 实用方法(将重构上面的 ReadAsJsonAsync 以也使用它):

public static class HttpUtil
{
public static JsonMediaTypeFormatter JsonFormatter => new JsonMediaTypeFormatter
{
SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
DateParseHandling = DateParseHandling.None
}.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)
};
}

当然欢迎对此解决方案提供反馈...

关于c# - 如何为 HttpClient (WinForms) 设置默认的 json 序列化设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48998670/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com