asp.net-web-apidelegatinghandler

Web Api Handler for pre-request


I am using the Delegating Handler of Web Api 2.0 to intercept all my Web Api calls and I need to act before the action is executed.

I implemented the code as explained on Microsoft Docs as following:

public class MyHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
       HttpRequestMessage request, 
       CancellationToken cancellationToken)
    {
        // do something
        return base.SendAsync(request, cancellationToken);
    }
}

And register the handler:

config.MessageHandlers.Add(new MyHandler());

But this code is executed after the controller method, which is not what I need. I want to execute the handler before, like I was doing on the pre-execute method of the old Action Filters for MVC.

Note I am not using the Action Filters because on Microsfot Docs they said to stop using the Action Filters for Web Api 2.0 because they will be deprecated. So, what's the alternative when working with Web Api?


Solution

  • Your Problem is most likely concurrent execution in different Tasks. That is because you do not await the base.SendAsync() Call.

    Something along these lines should probably solve your problem:

    var response = await base.SendAsync(request, cancellationToken);
    return response;
    

    The execution of the MessageHandler you've implemented is executed through the Web API pipeline to which you registered it through config.MessageHandlers.Add(new MyHandler()); and should be independent from any action filters

    If you are looking for addtional information look here.