简体   繁体   中英

How can I access a property from an ActionFilterAttribute in my ApiController?

I have a custom ActionFilterAttribute . For the sake of this question let's assume it's as follows:

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

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

My controller is then decorated with CustomActionFilter . What I am looking for is a way (in my controller method) to do something like:

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

If there is a more accepted way of doing this please let me know.

I discovered I could do the following to satisfy my problem:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM