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

本文关键字:ActionFilterAttribute 访问 属性 中的 ApiController 我的 | 更新日期: 2023-09-27 18:17:56

我有一个自定义的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?
    }
}

如果有更容易被接受的方法,请告诉我。

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

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

[CustomActionFilter]
public class MyController : ApiController {
    public ActionResult MyAction() {
        var myAttribute = ControllerContext
                          .ControllerDescriptor
                          .GetCustomAttributes<CustomActionFilter>()
                          .Single();
        var success = myAttribute.success;
    }
}
相关文章:
  • 没有找到相关文章