2012-05-09 16 views
2

在我的用户首次注册后,我希望他们必须在网站内填写个人资料页面。如果他们之前没有填写个人资料,我已将其设置为在登录时重定向他们,但如果他们在网站中输入另一个网址,他们当前可以随意在重定向之后去任何他们想要的地方。在查看ASP.NET MVC网站之前,您会如何“强制”用户填写个人资料?

在用户访问我网站上的任何页面之前,要求用户访问个人档案页面的最佳方式是什么?

这是最好的做了这样的事:'如果(!用户验证) - 重定向到配置文件页'放置在每个控制器的顶部?有没有更优雅的解决方案?

回答

4

开始实现自定义的行为过滤器(IActionFilter):

public class ProfileRequiredActionFilter : IActionFilter 
{ 
    #region Implementation of IActionFilter 

    public void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     //TODO: Check if the Authenticated User has a profile. 

     //If Authenicated User doesn't have a profile... 
     filterContext.Result = new RedirectResult("Path-To-Create-A-Profile"); 
    } 

    public void OnActionExecuted(ActionExecutedContext filterContext) 
    { 
    } 

    #endregion 
} 

然后在全球注册RegisterGlobalFilters内​​的行为过滤器方法的Global.asax ...

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new ProfileRequiredActionFilter()); 
} 

注意:如果你不希望这个过滤器在全球范围内应用,可以改为创建ActionFilterAttribute并将其应用到控制器和/或操作方法......

public class ProfileRequiredAttribute : ActionFilterAttribute 
{ 
    #region Implementation of IActionFilter 

    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     base.OnActionExecuting(filterContext); 

     //TODO: Check if the Authenticated User has a profile. 

     //If Authenicated User doesn't have a profile... 
     filterContext.Result = new RedirectResult("Path-To-Create-A-Profile"); 
    } 

    #endregion 
} 
3

您可以创建一个基本控制器,并让所有其他控制器继承它。 然后有一个OnActionExecuting方法,它像...

protected override void OnActionExecuting(ActionExecutingContext context) 
{ 
    base.OnActionExecuting(context); 

    // If the user has not filled out their profile, redirect them 
    if(CurrentUser != null && !CurrentUser.IsVerified) 
    { 
     context.Result = new RedirectResult("/User/Profile/" + CurrentUser.ID); 
    } 
} 
+0

我会建议从基本控制器移动它改为全局动作过滤器(IActionFilter)。通过不要求所有控制器继承基础控制器来执行配置文件检查,这样可以提供更大的灵活性。 –

+0

@RobRichardson我该怎么做呢? – Ecnalyr

+0

我结束了这种方法,因为我已经有权访问我的基础控制器中的'Custom Principal'属性。 –

相关问题