有很多关于如何检查ASP.NET MVC操作上是否存在装饰器的示例。 (例如How to disable a global filter in ASP.Net MVC selectively)
如何在Web Api端点上完成相同的操作?
谢谢
答案 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;