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

MVC中Application_BeginRequest引发localhost重定向次数过多问题求助

解决维护模式下的重定向循环问题

我完全懂你现在的困扰——本来想给用户一个清晰的维护提示,结果反而触发了浏览器的重定向限制,实在让人头疼。咱们先拆解问题根源,再一步步解决。

问题核心原因

你在Application_BeginRequest事件里做维护状态检测和重定向,但这个事件会触发每一个进入应用的请求,包括你跳转到维护页面的那个请求!也就是说:

  1. 用户请求任意页面 → 检测到维护模式 → 重定向到维护页
  2. 维护页的请求进入Application_BeginRequest → 再次检测到维护模式 → 又重定向到维护页
  3. 循环往复,直到浏览器判定重定向次数过多,抛出错误

解决方案:排除维护页面的请求

只需要在执行重定向前,先判断当前请求是否是维护页面本身,若是则跳过重定向逻辑,打破循环链。下面给你两种实用的实现方式:

方式1:通过请求路径判断(简单直接)

假设你的维护页面路径是/Maintenance/Index,修改代码如下:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var inMaintenanceMode = false;
    bool.TryParse(ConfigurationManager.AppSettings[Settings.Application.Modes.MaintenanceMode], out inMaintenanceMode);

    // 先检查当前请求是否是维护页面,避免循环
    var currentPath = HttpContext.Current.Request.Url.AbsolutePath;
    if (inMaintenanceMode && !currentPath.Equals("/Maintenance/Index", StringComparison.OrdinalIgnoreCase))
    {
        // 重定向到维护页面路由
        HttpContext.Current.Response.RedirectToRoute("MaintenanceRoute");
        // 终止后续请求处理,防止代码继续执行
        HttpContext.Current.Response.End();
    }
}

方式2:通过路由数据判断(更可靠)

如果担心路径判断出错,可以直接通过路由数据识别当前请求是否匹配维护页面的路由:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var inMaintenanceMode = false;
    bool.TryParse(ConfigurationManager.AppSettings[Settings.Application.Modes.MaintenanceMode], out inMaintenanceMode);

    if (inMaintenanceMode)
    {
        var context = HttpContext.Current;
        var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
        
        // 假设维护页的控制器是Maintenance,动作是Index
        if (routeData == null || 
            !routeData.Values["controller"].ToString().Equals("Maintenance", StringComparison.OrdinalIgnoreCase) ||
            !routeData.Values["action"].ToString().Equals("Index", StringComparison.OrdinalIgnoreCase))
        {
            context.Response.RedirectToRoute("Maintenance");
            context.Response.End();
        }
    }
}

额外注意事项

  • 务必调用Response.End()或HttpContext.Current.ApplicationInstance.CompleteRequest()终止请求处理,避免后续代码执行引发其他问题。
  • 如果维护页面依赖静态资源(CSS、图片、JS等),记得排除这些资源的重定向,否则维护页面会样式错乱。可以通过判断请求的文件扩展名实现:
    // 排除静态资源的示例
    var allowedExtensions = new[] { ".css", ".js", ".png", ".jpg", ".ico" };
    var extension = Path.GetExtension(currentPath);
    if (allowedExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase))
    {
        return; // 跳过重定向
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:18:39