2016-01-20 51 views
2

的執行我有一個自定義的行爲過濾器是這樣的:如何防止特定的自定義操作篩選

public class MySecurityTest : ActionFilterAttribut{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     //Do some security tests 
     base.OnActionExecuting(filterContext); 
    } 
} 

我補充這FilterConfig所有actions.but我需要一些行動,必定會工作。 現在我用的是這樣的:

public class MySecurityTest : ActionFilterAttribute 
{ 
    public bool CheckRules { get; set; } 

    public MySecurityTest(bool checkRules = true) 
    { 
     CheckRules = checkRules; 
    } 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (CheckRules) 
     { 
      //Do some security tests 
     } 
     base.OnActionExecuting(filterContext); 
    } 
} 

與用法:

[MySecurityTest(false)] 
public ActionResult Index() 
{ 
    return View(); 
} 

但如何能夠建立類似[AllowAnonymous]屬性

問候

回答

2

卻怎麼也構建類似[AllowAnonymous]屬性

很容易的實際上是:

[AttributeUsage(AttributeTargets.Method)] 
public class ExcludeMySecurityAttribute : Attribute 
{ 
} 

,然後在過濾器帳戶:

public class MySecurityTest : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(ExcludeMySecurityAttribute), true).Any()) 
     { 
      // The controller action is decorated with the exclude attribute 
      // so you should probably do nothing here 
     } 
     else 
     { 
      // Do your security tests here 
     } 
    } 
} 

現在,所有剩下的就是裝修:

[ExcludeMySecurity] 
public ActionResult Index() 
{ 
    return View(); 
} 
2

你只需要創建另一個屬性並使用.NET反射來檢查它的存在。

public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    if (!HasMyIgnoreAttribute(filterContext)) 
    { 
     //Do some security tests 
    } 
    base.OnActionExecuting(filterContext); 
} 

public bool HasMyIgnoreAttribute(ActionDescriptor actionDescriptor) 
{ 
    // Check if the attribute exists on the action method 
    bool existsOnMethod = actionDescriptor.GetCustomAttributes(typeof(MyIgnoreAttribute), false).Any(); 

    if (existsOnMethod) 
    { 
     return true; 
    } 

    // Check if the attribute exists on the controller 
    return actionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(MyIgnoreAttribute), false).Any(); 
} 

然後用自定義屬性來裝飾你的動作/控制器。

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)] 
public class MyIgnoreAttribute 
{ 
} 

使用

一般情況下,最好不要如果您使用依賴注入,因爲在this answer屬性should contain no behavior使用ActionFilterAttribute。您還應該考慮使用authorization filter(或AuthorizationAttribute-inherited類),而不是安全檢查的操作篩選器,因爲它在管道中較早完成。

相關問題