如何从ApiController中的ActionFilterAttribute访问属性?

时间:2014-08-14 14:34:24

标签: c# asp.net-web-api

我有自定义ActionFilterAttribute。为了这个问题,让我们假设它如下:

public class CustomActionFilterAttribute : ActionFilterAttribute {
    public bool success { get; private set };

    public override void OnActionExecuting(HttpActionContext actionContext) {
        //Do something and set success
        success = DoSomething(actionContext);
    }
}

然后我的控制器用CustomActionFilter修饰。我正在寻找的是一种方式(在我的控制器方法中)做类似的事情:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        //How do I get the 'success' from my attribute?
    }
}

如果有更多可接受的方式,请告诉我。

1 个答案:

答案 0 :(得分:6)

我发现我可以做以下事情来解决我的问题:

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        var myAttribute = ControllerContext
                          .ControllerDescriptor
                          .GetCustomAttributes<CustomActionFilter>()
                          .Single();
        var success = myAttribute.success;
    }
}