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

如何在global.asax中基于web.config时间键实现网站定时维护

解决方案:在Global.asax中实现网站定时维护拦截

我来帮你把维护逻辑从ActionFilter迁移到Global.asax中,完全满足你的需求——从web.config读取时段配置,在指定时间全局拦截请求并跳转到维护页面,同时沿用你提供的代码片段。


完整实现步骤

1. 完善Global.asax中的Application_BeginRequest事件

在Global.asax.cs文件中,我们利用Application_BeginRequest(每个请求开始时触发的全局事件)来实现维护判断和拦截。把以下代码添加到你的文件中:

protected void Application_BeginRequest()
{
    // 1. 从web.config读取维护时段配置,添加容错处理
    if (!int.TryParse(ConfigurationManager.AppSettings["StartTime"], out int startTime) ||
        !int.TryParse(ConfigurationManager.AppSettings["EndTime"], out int endTime))
    {
        // 配置读取失败时默认不启用维护,可根据需求调整逻辑
        return;
    }

    // 2. 判断当前请求是否处于维护时段
    DateTime currentTime = DateTime.Now;
    // 维护时段为:EndTime(下午6点)到次日StartTime(早8点)
    bool isUnderMaintenance = currentTime.Hour >= endTime || currentTime.Hour < startTime;

    if (isUnderMaintenance)
    {
        // 3. 沿用你提供的代码片段,跳转至维护页面
        var httpContext = HttpContext.Current;
        httpContext.Response.Clear();
        httpContext.ClearError();
        httpContext.Response.TrySkipIisCustomErrors = true;
        
        var routeData = new RouteData();
        // 匹配你之前使用的维护页面控制器和方法
        routeData.Values.Add("controller", "Undermaintenance");
        routeData.Values.Add("action", "Index");
        
        // 执行维护页面的控制器逻辑
        using (var controller = new UndermaintenanceController())
        {
            ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
        }
    }
}

2. 确认web.config配置正确性

确保你的web.config中存在对应的24小时制时段配置:

<appSettings>
    <add key="StartTime" value="8"/> <!-- 维护结束时间:早8点 -->
    <add key="EndTime" value="18"/> <!-- 维护开始时间:下午6点 -->
</appSettings>

关键细节说明

  • 全局拦截时机:选择Application_BeginRequest是因为它在请求处理的最早期触发,能拦截所有类型的请求(包括静态资源、API、页面等),比ActionFilter的拦截范围更广,更适合全局维护场景。
  • 配置容错处理:用int.TryParse处理配置读取,避免因配置格式错误导致网站崩溃,读取失败时默认跳过维护逻辑(你可以根据需求改成抛出错误或使用默认时段)。
  • 维护逻辑一致性:完全对齐你之前Attribute中的判断逻辑,确保维护时段为下午6点至次日早8点。
  • 代码复用:完整保留了你提供的响应清理、路由构建和控制器执行代码,仅调整了目标控制器的名称以匹配你的业务逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 13:57:47