像这样创建一个自定义 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());
}