2010-12-19 78 views
0

我有一個名爲「SomeController」的控制器。我想檢查用戶是否已登錄,或者是否有持續執行該控制器中的任何操作。要做到這一點,我讀到了那篇文章http://blog.wekeroad.com/blog/aspnet-mvc-securing-your-controller-actions/和我寫我自己的類(測試):ASP.NET MVC 2 OnActionExecuting方法的問題

public class BaseFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      FormsAuthentication.RedirectToLoginPage(); 
     } 
     //here will be checking the user permissions if he's logged in 
    } 
} 

[BaseFilter] 
public class SomeController : BaseController 
{ 
... 
} 

但你可以理解它使一個不定式環路時,我想從運行該控制器的任何行動。那麼,如何應對呢?

回答

1

您可以對相關方法應用操作過濾器,而不是在類級別。

就我個人而言,我會將其命名爲Authorize,然後將其應用於需要授權的控制器方法。

[Authorize] 
public ActionResult Index() 
{ 
// Do stuff 
}