2011-10-03 52 views
1

我有一個ActionFilter應用於我的基本控制器,它檢查請求和會話中的某些內容,並確保允許您查看請求的URI。禁止使用ActionFilter的特定頁面以外的所有頁面

直到現在,當我們需要禁止所有頁面(因爲它現在存在),但在這裏和那裏允許一些URI時,這一直很好地工作。

理想情況下,我會將屬性應用於我們想要允許的屬性,然後在過濾器中檢查該屬性並允許它存在,但我無法弄清楚如何在過濾器中實現該屬性。

任何想法或建議嗎?

+0

您是否嘗試在您的過濾器上添加參數並嘗試根據該參數忽略?讓說[CustomAttribute(「IgnoreThis」)] –

回答

0

我花了一個多小時試圖弄清楚這一點,然後我在這裏貼出來。幾分鐘後,它襲擊了我。

首先,我創建了一個屬性

public class AlwaysAllowAnonymousAttribute : Attribute {} 

其次,我打上我的行爲或控制器與上述屬性

最後,在我的ActionFilter我這樣做

public class VerifyResourceAccess : ActionFilterAttribute, IActionFilter 
{ 
    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) 
    { 

     var actionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AlwaysAllowAnonymousAttribute), false); 
     var controllerAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(AlwaysAllowAnonymousAttribute), false); 
     bool alwaysAllow = (actionAttributes.Length > 0) || (controllerAttributes.Length > 0); 

     if (!alwaysAllow) { 
      /* ... Some logic for checking if this user is allowed to access this resource ... */ 
     } 

     base.OnActionExecuting(filterContext); 
    } 
} 

的任何行動或標有該屬性的控制器將始終允許對其進行訪問。

相關問題