2015-10-23 4 views
2

Существует множество примеров того, как проверить, присутствует ли декоратор в действии ASP.NET MVC. (например, How to disable a global filter in ASP.Net MVC selectively)Фильтры Web Api - Проверьте, присутствует ли декоратор

Как я могу выполнить то же самое на конечной точке Web Api?

Спасибо

ответ

1

Хорошо, я только что узнал, как это сделать:

public class ValidateSomethingAttribute : ActionFilterAttribute 
{ 

    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 

     var isIgnorePresent = ((ReflectedHttpActionDescriptor)actionContext.ActionDescriptor).MethodInfo 
                            .CustomAttributes 
                            .Any(x => x.AttributeType == typeof(IgnoreValidateSomethingAttribute)); 
     if (isIgnorePresent) return; 
+0

Ваш код будет работать только в том случае, если 'ActionDescriptor' является' ReflectedHttpActionDescriptor' (т. Е. Не использовался поставщик дескрипторов пользовательских действий) и только для фильтров действий. –

3

Предполагая следующие атрибуты:

using System.Web.Http.Filters; 

public class CustomAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     // Does the action have the AnotherCustomAttribute attribute on it? 
     if (Enumerable.Any<AnotherCustomAttribute>((IEnumerable<AnotherCustomAttribute>)actionContext.ActionDescriptor.GetCustomAttributes<AnotherCustomAttribute>())) 
     { 
      // WebAPI action has your AnotherCustomAttribute attribute on it 
     } 

     base.OnActionExecuting(actionContext); 
    } 
} 

public class AnotherCustomAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     base.OnActionExecuting(actionContext); 
    } 
} 

Вы можете проверить наличие одного с помощью другого:

public class HomeController : ApiController 
{ 
    public HomeController() 
    { 
    } 

    [CustomAttribute] // Checks for presence of 'AnotherCustomAttribute' 
    [AnotherCustomAttribute] 
    public object Get(int id) 
    { 
     return "test"; 
    } 
} 

NB: используется ActionFilterAttribute из пространства имен System.Web.Http.Filters, а не System.Web.Mvc.

Смежные вопросы