你可以试试这个。http://blog.tomasjansson.com/2011/08/securing-your-asp-net-mvc-3-application/
更新
以下代码工作正常。它在基类本身中实现 OnAuthorization。
public class MyBaseController : Controller
{
protected override void OnAuthorization(AuthorizationContext filterContext)
{
var skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) ||
filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(
typeof(AllowAnonymousAttribute), true);
if (!skipAuthorization)
{
base.OnAuthorization(filterContext);
if (!User.Identity.IsAuthenticated)//Implement your own logic here
{
var url = new UrlHelper(filterContext.RequestContext);
var logonUrl = url.Action("LogOn", "Home", new { reason = "NotAuthorized" });
filterContext.Result = new RedirectResult(logonUrl);
}
}
}
}
public class HomeController : MyBaseController
{
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
public ActionResult PasswordReset()
{
return Content("reset your password");
}
[AllowAnonymous]
public ActionResult LogOn(string reason)
{
return Content("please log in");
}
}
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class AllowAnonymousAttribute : Attribute
{
}