Web Api过滤器 - 检查是否存在装饰器

时间:2015-10-23 14:51:18

标签: asp.net-mvc asp.net-web-api

有很多关于如何检查ASP.NET MVC操作上是否存在装饰器的示例。 (例如How to disable a global filter in ASP.Net MVC selectively

如何在Web Api端点上完成相同的操作?

谢谢

2 个答案:

答案 0 :(得分: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";
    }
}

注意:这会使用ActionFilterAttribute命名空间中的System.Web.Http.Filters而不是System.Web.Mvc

答案 1 :(得分: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;