0

I have an MVC4 Intranet application (using the default template). I am using Windows Authentication as my login system, however, i want to be able to capture some details from the user the first time they register with the site.

Use Cases

  1. First time user authenticates using their AD login (currently working). They are presented with an 'Enter your Details' View.
  2. Second time user authenticates using their AD login. They are taken straight to the home screen.

Cheers, Dave

4

1 回答 1

2

像这样创建一个自定义 AuthorizeAttribute:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    private UnitOfWork _unitOfWork = new UnitOfWork();

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var isAuthorized = false;
        var username = httpContext.User.Identity.Name;
        // Some code to find the user in the database...
        var user = _unitOfWork.UserRepository.Find(username);
        if(user != null)
        {
           // Check if there are Details for the user in the database
           if(user.HasDetails)
           {
             isAuthorized = true;
           }
        }


        return isAuthorized;
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {            
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        if (!AuthorizeCore(filterContext.HttpContext))
        {
           // If not authorized, redirect to the Details action 
           // of the Account controller... 

           var action = filterContext.RouteData.Values["action"];
           if(filterContext.Controller is AccountController 
             && action.Equals("Details"))
           {
             // Do nothing
           }
           else
           {
             filterContext.Result = new RedirectToRouteResult(
               new System.Web.Routing.RouteValueDictionary {
                 {"controller", "Account"}, {"action", "Details"}
               }
             );
           }               
        }
    }
}

然后,您可以像这样在控制器中使用它:

[MyAuthorize]
public class HomeController : Controller
{
}

或者,您可以将其注册为 Global.asax 文件中的全局操作过滤器,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyAuthorizeAttribute());
}
于 2013-08-13T02:41:30.670 回答