gpt4 book ai didi

c# - 如何根据每个请求更改 JsonSerializerSettings

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

我想为 DateTime 使用不同的格式关于查询字符串参数的字段:即如果查询字符串包含 dateFormat=iso参数,我想返回 ISO 6801 中的日期:

{
"date": "2018-03-27T12:20:34.248563Z"
}

但是如果查询字符串包含dateFormat=unix参数,我想以 UNIX 时间返回日期:

{
"date": 1522152517
}

使用 JsonResult 很容易实现和 ResultFilter :

public class DateFormatResultFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(ResultExecutingContext context,ResultExecutionDelegate next)
{
var dateTimeFormat = context.HttpContext.Request.Query["dateFormat"].FirstOrDefault() ?? "iso8601";
var converter = GetConverter(dateTimeFormat);

var jsonSettings = context.HttpContext.RequestServices
.GetRequiredService<IOptionsSnapshot<MvcJsonOptions>>()
.Value.SerializerSettings;

jsonSettings.Converters.Add(converter);

if (context.Result is JsonResult jsonResult)
{
var value = jsonResult.Value;


context.Result = new JsonResult(value, jsonSettings);
}
await next();
}
}

我不想争夺全局JsonSerializerSettings , 所以我决定 IOptionsSnapshot<MvcJsonOptions>而不是 IOptions<MvcJsonOptions> .

但是我怎样才能为 ObjectResult 实现这种行为呢? ?

最佳答案

至于 ObjectReault,您可以使用新的 JsonOutputFilter 和所需的 JsonSerializerSettings 创建一个新的 ObjectResult:

var jsonSerializationSettings = ...;
if (context.Result is ObjectResult objectResult)
{
var result = new ObjectResult(objectResult.Value)
{
ContentTypes = objectResult.ContentTypes,
DeclaredType = objectResult.DeclaredType,
StatusCode = objectResult.StatusCode,
Formatters = new FormatterCollection<IOutputFormatter>(objectResult.Formatters)
};
result.Formatters.RemoveType<JsonOutputFormatter>();
result.Formatters.Add(new JsonOutputFormatter(jsonSerializationSettings, ArrayPool<char>.Shared));
context.Result = result;
}

关于c# - 如何根据每个请求更改 JsonSerializerSettings,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49513000/

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