我的建议是使用ActionFilter代替。它会容易得多。你可以做这样的事情:
public class RequiresAuthenticationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// You can do any custom authentication logic in here
if (User == null || !User.Identity.IsAuthenticated)
{
// This assumes that Account is the controller, and Logon is the action method.
// You might want to check your routes if this is still not working correctly
RedirectToAction("Logon", "Account");
}
}
}
这将让那么你只是把一个属性上的操作方法,在你的控制器像这样:
[RequiresAuthentication]
public ActionResult Index()
{
return View();
}
或者,正如其他人所指出的那样,如果你不需要任何自定义的验证逻辑,你可以只使用AuthorizeAttribute:
[Authorize]
public ActionResult Index()
{
return View();
}
这已经内置见授权属性 – terjetyl 2009-07-28 14:24:45