You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在每个请求中修改JsonSerializerSettings,按查询参数返回不同日期格式

刚好做过类似的需求!在ASP.NET Core里,用JsonResult搭配自定义ResultFilter就能完美实现根据查询字符串动态切换日期返回格式的需求,具体实现步骤如下:

实现根据查询字符串动态调整日期返回格式

1. 自定义ResultFilter处理逻辑

我们需要创建一个实现IAsyncResultFilter的过滤器类,它会拦截请求的返回结果,根据查询参数dateFormat来调整日期的序列化方式:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Text.Json;
using System.Text.Json.Serialization;

public class DateFormatResultFilter : IAsyncResultFilter
{
    public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next)
    {
        // 从查询字符串中获取dateFormat参数
        var dateFormatParam = context.HttpContext.Request.Query["dateFormat"].FirstOrDefault()?.ToLower();
        
        // 只处理JsonResult类型的返回结果
        if (context.Result is JsonResult jsonResult)
        {
            var serializerOptions = jsonResult.SerializerOptions ?? new JsonSerializerOptions();
            
            switch (dateFormatParam)
            {
                case "iso":
                    // 配置为ISO 8601格式序列化
                    serializerOptions.DateFormatHandling = JsonDateFormatHandling.IsoDateFormat;
                    serializerOptions.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
                    jsonResult.SerializerOptions = serializerOptions;
                    break;
                case "unix":
                    // 将DateTime字段转换为Unix时间戳(这里以动态对象为例,强类型可通过反射/自定义Converter优化)
                    if (jsonResult.Value is IDictionary<string, object> responseDict)
                    {
                        if (responseDict.TryGetValue("date", out var dateObj) && dateObj is DateTime date)
                        {
                            // 转换为秒级Unix时间戳(如需毫秒级可改用ToUnixTimeMilliseconds)
                            responseDict["date"] = new DateTimeOffset(date).ToUnixTimeSeconds();
                        }
                    }
                    break;
            }
        }

        // 继续执行后续的结果处理逻辑
        await next();
    }
}

2. 注册过滤器

全局注册(所有接口生效)

在Program.cs(ASP.NET Core 6及以上版本)中添加全局过滤器:

builder.Services.AddControllers(options =>
{
    options.Filters.Add<DateFormatResultFilter>();
});

局部注册(仅特定控制器/Action生效)

如果只想让部分接口支持这个功能,可以在控制器或Action上标记特性:

[ServiceFilter(typeof(DateFormatResultFilter))]
public class DateController : ControllerBase
{
    [HttpGet]
    public IActionResult GetCurrentDate()
    {
        return Json(new { date = DateTime.UtcNow });
    }
}

3. 测试效果

调用接口时通过查询参数指定格式:

  • 当请求 GET /api/date/getcurrentdate?dateFormat=iso,返回结果:
    { "date": "2018-03-27T12:20:34.248563Z" }
    
  • 当请求 GET /api/date/getcurrentdate?dateFormat=unix,返回结果:
    { "date": 1522152517 }
    

优化提示

如果你的接口返回的是强类型对象,可以自定义一个JsonConverter来处理DateTime到Unix时间戳的转换,这样比遍历字典更优雅,也能适配复杂对象结构。

内容的提问来源于stack exchange,提问作者Sane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:25:36