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

如何在Hangfire的作业参数中格式化time字段?

解决Hangfire作业参数中time字段可读性问题

问题背景

Hangfire失败/已执行作业的参数页面中,time字段默认以原始序列化格式展示(如/Date(1620000000000)/或ISO字符串),可读性极差,修改web.config区域设置无法解决该问题。

无需修改源码的解决方案

1. 前端注入脚本格式化(兼容历史作业)

通过自定义Hangfire Dashboard渲染器,注入前端脚本自动转换时间格式,对新、旧作业都生效:

  • 实现自定义DashboardRenderer:
    public class CustomDashboardRenderer : DefaultDashboardRenderer
    {
        protected override void RenderScripts(DashboardContext context)
        {
            base.RenderScripts(context);
            context.Response.Write("<script>");
            context.Response.Write(@"
                document.addEventListener('DOMContentLoaded', function() {
                    document.querySelectorAll('div.parameter-value code').forEach(el => {
                        const text = el.textContent.trim();
                        // 处理JSON.NET旧日期格式
                        if (text.startsWith('\"/Date(')) {
                            const timestamp = parseInt(text.match(/\d+/)[0]);
                            el.textContent = new Date(timestamp).toLocaleString();
                        } 
                        // 处理ISO格式日期
                        else if (Date.parse(text)) {
                            el.textContent = new Date(text).toLocaleString();
                        }
                    });
                });
            ");
            context.Response.Write("</script>");
        }
    }
    
  • 注册自定义渲染器:
    GlobalConfiguration.Configuration.UseDashboardRenderer(new CustomDashboardRenderer());
    

2. 自定义参数序列化(仅对新作业生效)

从源头修改DateTime参数的序列化格式,让存储的参数本身就是可读格式:

  • 实现自定义DateTime转换器:
    public class ReadableDateTimeConverter : IsoDateTimeConverter
    {
        public ReadableDateTimeConverter()
        {
            DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
        }
    }
    
  • 配置Hangfire使用该转换器:
    var jsonSettings = new JsonSerializerSettings();
    jsonSettings.Converters.Add(new ReadableDateTimeConverter());
    GlobalConfiguration.Configuration.UseSerializerSettings(jsonSettings);
    
    注意:此方案仅影响新提交的作业,历史作业的已存储参数无法变更。

终极方案(不推荐)

若上述方案无法满足需求,可克隆Hangfire源码,修改参数页面的时间字段渲染逻辑,重新编译部署。但此方式会增加后续版本升级的维护成本,需谨慎使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:38:27