2017-01-12 166 views
1

如果我在FilterConfig.cs註冊一個全球Authorize屬性,這樣每個動作方法只能是通過身份驗證的用戶訪問,且裝飾一些控制器,[Authorize(Role="Admin")]這樣只有管理員用戶可以訪問它們,是否授權邏輯運行兩次在這些控制器上?我能做些什麼來防止這種情況發生?ASP.NET MVC授權過濾

+0

您可以使用條件過濾器,以避免重複過濾器..在這裏,你可以定義哪些屬性應該得到裝飾的操作或控制器你的選擇。 http://haacked.com/archive/2011/04/25/conditional-filters.aspx/ –

回答

1

您可以使用ASP.NET MVC「FilterProvider」提供程序。這將幫助你從特定的控制器和操作中獲取所有相關的過濾器。

所以你可以定義你自己的提供者並且註冊那個而不是默認的提供者。這會讓你完全控制asp.net過濾器,你可以根據你的需求刪除一些過濾器。

可以說我們有以下控制器。

[Authorize] 
public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Whatever() 
    { 
     return View(); 
    } 

} 

我認爲你正在尋找一種方法來做如下的事情。專注於指數動作

[Authorize] 
public class HomeController : Controller 
{ 
    [ExcludeFilter(typeof(AuthorizeAttribute))] // Excluding Authorize Important ! 
    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult Admin() // will follow the declared authorize Attribute 
    { 
     return View(); 
    } 
} 

如果那是你正在尋找,然後看到這個Article