In a message handler, a series of message handlers are chained together. The first handler receives the HTTP request, does some processing, and then hands the request to the next handler. At some point, a response is created and returned to the chain. This pattern is called Delegated Handler.
In addition to the built-in server-side message handlers, we can also create our own server-side HTTP message handlers. Create custom server-side HTTP For message handlers in ASP.NET Web API, we use DelegatingHandler. We have to create a class derived from System.Net.Http.DelegatingHandler. The custom class should then override the SendAsync method.
Task
This method takes HttpRequestMessage as input and returns asynchronously HttpResponseMessage. A typical implementation performs the following operations:
public class CustomMessageHandler : DelegatingHandler{ protected async override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken){ Debug.WriteLine("CustomMessageHandler processing the request"); // Calling the inner handler var response = await base.SendAsync(request, cancellationToken); Debug.WriteLine("CustomMessageHandler processing the response"); return response; } }
Delegate handlers can also skip the inner handler and create the response directly.
public class CustomMessageHandler: DelegatingHandler{ protected override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken){ // Create the response var response = new HttpResponseMessage(HttpStatusCode.OK){ Content = new StringContent("Skipping the inner handler") }; // TaskCompletionSource creates a task that does not contain a delegate var taskCompletion = new TaskCompletionSource<HttpResponseMessage>(); taskCompletion.SetResult(response); return taskCompletion.Task; } }
The above is the detailed content of What is the usage of DelegatingHandler in Asp.Net webAPI C#?. For more information, please follow other related articles on the PHP Chinese website!