c# - 在flur PostJsonAsync中将枚举序列化为字符串
问题描述
在控制台应用程序中,我使用 Flurl 包向 api 发送请求(api 现在无法正常工作)。我正在尝试验证序列化是否按预期发生。我希望枚举类型被序列化为字符串。程序:
class Program
{
private static async Task HandleFlurlErrorAsync(HttpCall call)
{
string body = call.RequestBody;
}
static async Task Main(string[] args)
{
FlurlHttp
.Configure(settings =>
{
settings.OnErrorAsync = HandleFlurlErrorAsync;
});
var model = new SearchBy
{
SearchCategory = SearchCategory.TimeStamp
};
var person = await "https://api.com".PostJsonAsync(model);
}
}
楷模:
public class SearchBy
{
[JsonConverter(typeof(StringEnumConverter))]
public SearchCategory SearchCategory { get; set; }
}
public enum SearchCategory
{
TimeStamp,
ModifiedDate,
}
请求正文的序列化结果是{"SearchCategory":0}
我期望的结果{"SearchCategory":"TimeStamp"}
。我遵循了
JavaScriptSerializer - JSON serialization of enum as string中提供的解决方案
但似乎不起作用。是否需要进行任何配置或设置才能达到预期。
解决方案
我自己找到了解决方案。在 flurl 配置中添加了一个转换器,如下所示。
FlurlHttp
.Configure(settings =>
{
var jsonSettings = new JsonSerializerSettings();
jsonSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
settings.OnErrorAsync = HandleFlurlErrorAsync;
settings.JsonSerializer = new NewtonsoftJsonSerializer(jsonSettings);
});
推荐阅读
- katalon-studio - Katalon Studio 中的 Web 元素突出显示或变灰?
- asp.net-core - 身份服务器 4 上的“客户端密码验证失败”错误
- mongodb - KMongo 是否支持枚举?
- powerbi - 使用函数转换表列
- highcharts - 如何在 Highcharts 中为图案添加背景?
- pdf - Mac 上的 WkWebView PDF 导出
- kubernetes - K8s:StatefulSet如何在失败的情况下增加重新启动pod之间的时间
- c# - LINQ - 按相同功能过滤和排序的最有效方法
- javascript - 如何在没有表单的情况下通过 Ajax 和 php 上传文件?
- mysql - 如何从 RAM 在 1 MB 到 2 GB 之间的数据库表中获取所有设备?