我的建議是使用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