I'm writting a ASP.NET WEB API.
Once the Action is executed i want to call a method.
For example:
public string Action1(object a)
{
// ...
// call method1();
return "sample1";
}
public string Action2(object b)
{
// ...
// call method1();
return "sample2";
}
Is there a way to call method1() on every action without mentioning in every action?
You can implement an custom System.Web.Http.Filters.ActionFilterAttribute and call method1() inside OnActionExecuted(...):
public class MyActionFilter : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// call method1();
// ...
base.OnActionExecuted(actionExecutedContext);
}
}
You can then use this [MyActionFilter] on the action, on the controller, or add it to the global config in WebApiConfig.cs:
config.Filters.Add(new MyActionFilter());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With