user1135534
user1135534

Reputation: 575

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?

Upvotes: 4

Views: 1677

Answers (1)

Maggie Ying
Maggie Ying

Reputation: 10175

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());

Upvotes: 10

Related Questions