2010-08-18 107 views
3

我希望我的MVC应用程序检查(每个请求)如果当前用户有一个配置文件。如果找不到配置文件,我想将它们重定向到“配置文件”页面以供它们提交。ASP.NET MVC重定向困境Application_AuthenticateRequest

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.HasProfile()”来检查用户是否有配置文件。它的工作原理,但问题是那Application_AuthenticateRequest被调用为每一个请求,包括JavaScript,CSS等...

此外,它创建了一个重定向循环,当我尝试做Response.RedirectToRoute(“档案” )。

我围绕着这一发现的唯一办法就是重定向到的个人资料页面之前,添加以下到我的IF语句:

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

它检查当前路径不是个人资料页(防止重定向循环)以及URL中是否存在句点(以允许javascript和css资源继续加载)。 有没有更好的方法?你们如何处理这个问题?

回答

3

我不确定这是否适用于每一种情况,但我发现可以询问当前上下文的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... 

}