我的用户第一次注册后,我希望他们必须在网站内填写个人资料页面。如果他们之前没有填写过个人资料,我会设置它以便在登录期间重定向它们,但是如果他们在网站中输入另一个网址,他们目前可以在重定向后自由地去任何他们想要的地方。
在用户尝试访问我网站上的任何网页,直到他们完成个人资料后,要求用户访问个人资料页面的最佳方法是什么?
最好用以下内容完成:'if(!用户已验证) - 重定向到配置文件页面'放置在每个控制器的顶部?有更优雅的解决方案吗?
答案 0 :(得分: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
}
然后在Global.asax的 RegisterGlobalFilters 方法中全局注册Action Filter ...
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ProfileRequiredActionFilter());
}
注意:如果您不希望全局应用此过滤器,则可以创建ActionFilterAttribute并将其应用于Controllers和/或Action方法......
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
}
答案 1 :(得分:3)
您可以创建一个Base控制器,让所有其他控制器继承该控制器。 然后在其中有一个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);
}
}