Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnActionExecuted being called twice in Web API

I am trying to do some stuff after my controller is done with the action at OnActionExecuted. However the method is called twice.

My filter method

public class TestFilter: ActionFilterAttribute
{
  public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {

       //do stuff here


    }
}

and my controller

[TestFilter]
  public class BaseController : ApiController
{
 public LoginResponseDTO Login(LoginRequestDTO loginRequestDTO)
    {

 //do login stuff
    }

}

when i try this filter, the onActionExecuted Method gets called twice which causes my action in the method to be applied twice to the response. I have searched for a reason but cannot find a solution.

Any Ideas?

like image 858
keremsefa Avatar asked Nov 26 '13 14:11

keremsefa


3 Answers

The answer is from @Martijn comments above:

 [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
 public class TestFilter: ActionFilterAttribute

All credits goes to him. (Note: I'll remove the post, if he decide to add the comment as answer)

like image 67
lowselfesteemsucks Avatar answered Nov 14 '22 20:11

lowselfesteemsucks


For me the issue was I was calling /myApi/action which was redirecting to /myApi/action/ and this caused OnActionExecuted() to run twice.

I filtered out where filterContext.Result is RedirectResult within OnActionExecuted since I wasn't interested in running my code then. The HTTP status code showed as 200 on both the calls so filtering by that won't work.

like image 24
C.M. Avatar answered Nov 14 '22 22:11

C.M.


If you have registered the custom filter in Global.asax.cs, like this:

GlobalConfiguration.Configuration.Filters.Add(new TestFilterAttribute());

Please revoke the attribute above your custom controller.

like image 1
auxo Avatar answered Nov 14 '22 22:11

auxo