2011-09-19 12 views
2

我有一個應用程序需要授權才能訪問所有控制器/操作。除了登錄錯誤控制器/操作如果我所有的.Net控制器/操作都需要授權Attr,爲什麼沒有一個屬性只能使用那些不需要的?

在這種情況下,在一次防守方式工作是更好地保持默認限制對所有控制器/操作(無授權屬性)和一個自定義選擇屬性只有那些誰不知道。

你們這樣做過嗎?

我有一個MVC過濾如果登錄的用戶有機會獲得他們的所有行動之前執行:

public class ValidatePermissionAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext context) 
    { 
     bool isAuthorized = false; 

     //Logic that verify if logged user have permission to access the requested Controller/Action 
     ... 

     //Redirect to a page Error if Logged User don't have Authorization 
     if (!isAuthorized) 
     { 
      RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary(); 
      redirectTargetDictionary.Add("action", "Erro"); 
      redirectTargetDictionary.Add("controller", "Index"); 

      context.Result = new RedirectToRouteResult(redirectTargetDictionary); 
     } 
    } 
} 

我想做到這一點的最好辦法。我可以創建一個空白定製屬性及放在控制器不需要授權,並檢查它在我過濾

public class ValidatePermissionAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext context) 
    { 
     bool isAuthorized = false; 

     var DoNotRequiresAuthorizationAttributes = context.ActionDescriptor.GetCustomAttributes(typeof(DoNotRequiresAuthorizationAttribute), false); 

     if (DoNotRequiresAuthorizationAttributes.Length > 0) 
      isAuthorized = true; 

     ... 

     //Redirect to a page Error if Logged User don't have Authorization 
     if (!isAuthorized) 
     { 
      RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary(); 
      redirectTargetDictionary.Add("action", "Erro"); 
      redirectTargetDictionary.Add("controller", "Index"); 

      context.Result = new RedirectToRouteResult(redirectTargetDictionary); 
     } 
    } 
} 

什麼各位高手你們認爲?

更新:

思考更好,我可以在Global.asax中取代我篩選自定義授權屬性並註冊在所有控制器ACT /動作

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new MyCustomAuthorizeAttribute()); 
} 

更新2:

而是創建一個空白定製屬性及放在控制器不需要授權,我通過我的自定義授權參數的控制器不需要授權(在Global.asax中):

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
{ 
    filters.Add(new ValidatePermissionAttribute("Login", "Erro")); 
} 

我授權屬性:

​​

更新3:

條件篩選器是要走的路。

+0

我喜歡這個方法...... – David

+0

@David,全局和條件過濾器是標準的方法。 :) – bzlm

+0

不,srsly ?! :-X – David

回答

2

如果目標只是減少需要重新申報在許多地方的屬性,似乎人們可以通過屬性創建一個抽象AuthorizeController達到同樣的,任何控制他們的行動都需要授權可以繼承。

6

幾種方式來處理屬性的批量實現:

我一直在發行前向使用的過濾器屬性,其結果可以通過輸出緩存緩存,然後這個止跌不會跑。最好實現一個IAuthorizationFilter接口(或AuthorizeAttribute類),然後創建一個授權過濾器。

+1

而不是創建自定義控制器基類我可以在Global.asax中註冊我的屬性。你怎麼看? –

+3

@Acaz,如果你的意思是'GlobalFilters.Filters.Add(new MyActionFilterAttribute());',那麼這就是這個答案所暗示的。 – bzlm

+0

@Acaz是的,應該很適合你在全球範圍內應用。 –

相關問題