Asp.net mvc 你会怎样';力';用户在查看ASP.NET MVC站点之前是否要填写配置文件?

Asp.net mvc 你会怎样';力';用户在查看ASP.NET MVC站点之前是否要填写配置文件?,asp.net-mvc,redirect,asp.net-membership,profile,Asp.net Mvc,Redirect,Asp.net Membership,Profile,在我的用户第一次注册后,我希望他们必须在网站内填写个人资料页面。我已经设置好了它,如果他们之前没有填写个人资料,那么它会在登录时重定向他们,但是如果他们在网站中键入另一个url,在重定向之后,他们现在可以自由地去任何他们想去的地方 当用户试图访问我网站上的任何页面直到完成配置文件时,要求用户访问配置文件页面的最佳方式是什么 如果在每个控制器的顶部放置类似“如果(!用户已验证)-重定向到配置文件页”的内容,是否可以最好地完成此操作?有更优雅的解决方案吗?您可以创建一个基本控制器,并让所有其他控制器

在我的用户第一次注册后,我希望他们必须在网站内填写个人资料页面。我已经设置好了它,如果他们之前没有填写个人资料,那么它会在登录时重定向他们,但是如果他们在网站中键入另一个url,在重定向之后,他们现在可以自由地去任何他们想去的地方

当用户试图访问我网站上的任何页面直到完成配置文件时,要求用户访问配置文件页面的最佳方式是什么


如果在每个控制器的顶部放置类似“如果(!用户已验证)-重定向到配置文件页”的内容,是否可以最好地完成此操作?有更优雅的解决方案吗?

您可以创建一个基本控制器,并让所有其他控制器继承它。 然后在其中有一个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);
    }
}

从实现自定义操作筛选器(IActionFilter)开始:

然后在Global.asax的RegisterGlobalFilters方法中全局注册操作筛选器

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
}

我建议将其从基本控制器移动到全局操作过滤器(IActionFilter)。通过不要求所有控制器继承基本控制器来执行配置文件检查,这为您提供了更大的灵活性。@RobRichardson我该怎么做呢?我最终选择了这种方法,因为我已经可以访问基本控制器中的“自定义主体”属性。
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
}