2
Reply

what is delegate handler in web api?

Ravi Patel

Ravi Patel

10y
4.5k
0
Reply

    Hello @ tomb of the mask, in ASP.NET Web API, a DelegatingHandler is a component that sits in the HTTP request/response pipeline and can inspect or modify requests before they reach the controller, and responses after the controller has processed them.

    Think of it like middleware or a filter that wraps around the API request.

    Simple example

    public class LoggingHandler : DelegatingHandler
    {protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken){// Before the request reaches the controllerConsole.WriteLine($"Request: {request.Method} {request.RequestUri}");var response = await base.SendAsync(request, cancellationToken);// After the controller has returnedConsole.WriteLine($"Response: {response.StatusCode}");return response;}
    }

    The flow is roughly:

    HTTP Request↓
    DelegatingHandler↓
    Authentication / Logging / Other handlers↓
    Controller↓
    DelegatingHandler↓
    HTTP Response

    Delegate handler use to track the incoming request in your web api project, so we register delegate handler in global.asax file after creation, it may be useful in tracking for request and response for request coming for actions.