代码之家  ›  专栏  ›  技术社区  ›  Derek Hunziker

ASP.NET MVC应用程序重定向困境

  •  3
  • Derek Hunziker  · 技术社区  · 15 年前

    我希望我的MVC应用程序检查(在每个请求中)当前用户是否有配置文件。如果找不到配置文件,我想将它们重定向到“配置文件”页面,让它们提交一个。

        protected void Application_AuthenticateRequest()
        {
            if (HttpContext.Current.User != null)
            {
                // Redirect to profile page if the current user does not have a profile
                if (!HttpContext.Current.User.HasProfile())
                    Response.RedirectToRoute("Profile");
            }
        }
    

    我已经扩展了iprincipal以包含一个方法“user.has profile()”,以检查用户是否有配置文件。它起作用了, 但问题是,每个请求都会调用应用程序的authenticateRequest,包括javascript、css等。

    此外,当我尝试响应时,它会创建一个重定向循环。

    我找到的唯一方法是在重定向到配置文件页之前将以下内容添加到if语句中:

    !HttpContext.Current.User.HasProfile() && Request.Path != "/system/profile" && !Request.Path.Contains(".")
    

    它检查当前路径是否不是配置文件页(以防止重定向循环),以及URL中是否有句点(以允许继续加载javascript和css资源)。 有更好的方法吗?你们是怎么处理的?

    1 回复  |  直到 13 年前
        1
  •  3
  •   Tom Lianza    15 年前

    我不确定这是否适用于每种情况,但我发现您可以询问当前上下文的handler属性,对于静态资源,它为空。

    void LogRequestInfo(object sender, EventArgs e)
    {
    
            HttpApplication app = (HttpApplication)sender;
            HttpContext ctx = app.Context;
    
            // We don't want to spend resources logging static file requests.  This code was added when we moved
            // to Integrated mode in IIS.
            if (ctx.Handler == null)
                return;
    
    // More code below here...
    
    }