Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire certain method after every action in Web APi

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?

like image 900
user1135534 Avatar asked Nov 01 '25 22:11

user1135534


1 Answers

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());
like image 61
Maggie Ying Avatar answered Nov 04 '25 20:11

Maggie Ying



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!