"
ASP.NET (snapshot 2017) Microsoft documentation and samples

HTTP Message Handlers in ASP.NET Web API

by Mike Wasson

A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

Typically, a series of message handlers are chained together. The first handler receives an HTTP request, does some processing, and gives the request to the next handler. At some point, the response is created and goes back up the chain. This pattern is called a delegating handler.

Server-Side Message Handlers

On the server side, the Web API pipeline uses some built-in message handlers:

You can add custom handlers to the pipeline. Message handlers are good for cross-cutting concerns that operate at the level of HTTP messages (rather than controller actions). For example, a message handler might:

This diagram shows two custom handlers inserted into the pipeline:

[!NOTE] On the client side, HttpClient also uses message handlers. For more information, see HttpClient Message Handlers.

Custom Message Handlers

To write a custom message handler, derive from System.Net.Http.DelegatingHandler and override the SendAsync method. This method has the following signature:

[!code-csharpMain]

   1:  Task<HttpResponseMessage> SendAsync(
   2:      HttpRequestMessage request, CancellationToken cancellationToken);

The method takes an HttpRequestMessage as input and asynchronously returns an HttpResponseMessage. A typical implementation does the following:

  1. Process the request message.
  2. Call base.SendAsync to send the request to the inner handler.
  3. The inner handler returns a response message. (This step is asynchronous.)
  4. Process the response and return it to the caller.

Here is a trivial example:

[!code-csharpMain]

   1:  public class MessageHandler1 : DelegatingHandler
   2:  {
   3:      protected async override Task<HttpResponseMessage> SendAsync(
   4:          HttpRequestMessage request, CancellationToken cancellationToken)
   5:      {
   6:          Debug.WriteLine("Process request");
   7:          // Call the inner handler.
   8:          var response = await base.SendAsync(request, cancellationToken);
   9:          Debug.WriteLine("Process response");
  10:          return response;
  11:      }
  12:  }

[!NOTE] The call to base.SendAsync is asynchronous. If the handler does any work after this call, use the await keyword, as shown.

A delegating handler can also skip the inner handler and directly create the response:

[!code-csharpMain]

   1:  public class MessageHandler2 : DelegatingHandler
   2:  {
   3:      protected override Task<HttpResponseMessage> SendAsync(
   4:          HttpRequestMessage request, CancellationToken cancellationToken)
   5:      {
   6:          // Create the response.
   7:          var response = new HttpResponseMessage(HttpStatusCode.OK)
   8:          {
   9:              Content = new StringContent("Hello!")
  10:          };
  11:   
  12:          // Note: TaskCompletionSource creates a task that does not contain a delegate.
  13:          var tsc = new TaskCompletionSource<HttpResponseMessage>();
  14:          tsc.SetResult(response);   // Also sets the task state to "RanToCompletion"
  15:          return tsc.Task;
  16:      }
  17:  }

If a delegating handler creates the response without calling base.SendAsync, the request skips the rest of the pipeline. This can be useful for a handler that validates the request (creating an error response).

Adding a Handler to the Pipeline

To add a message handler on the server side, add the handler to the HttpConfiguration.MessageHandlers collection. If you used the “ASP.NET MVC 4 Web Application” template to create the project, you can do this inside the WebApiConfig class:

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          config.MessageHandlers.Add(new MessageHandler1());
   6:          config.MessageHandlers.Add(new MessageHandler2());
   7:   
   8:          // Other code not shown...
   9:      }
  10:  }

Message handlers are called in the same order that they appear in MessageHandlers collection. Because they are nested, the response message travels in the other direction. That is, the last handler is the first to get the response message.

Notice that you don’t need to set the inner handlers; the Web API framework automatically connects the message handlers.

If you are self-hosting, create an instance of the HttpSelfHostConfiguration class and add the handlers to the MessageHandlers collection.

[!code-csharpMain]

   1:  var config = new HttpSelfHostConfiguration("http://localhost");
   2:  config.MessageHandlers.Add(new MessageHandler1());
   3:  config.MessageHandlers.Add(new MessageHandler2());

Now let’s look at some examples of custom message handlers.

Example: X-HTTP-Method-Override

X-HTTP-Method-Override is a non-standard HTTP header. It is designed for clients that cannot send certain HTTP request types, such as PUT or DELETE. Instead, the client sends a POST request and sets the X-HTTP-Method-Override header to the desired method. For example:

[!code-consoleMain]

   1:  X-HTTP-Method-Override: PUT

Here is a message handler that adds support for X-HTTP-Method-Override:

[!code-csharpMain]

   1:  public class MethodOverrideHandler : DelegatingHandler      
   2:  {
   3:      readonly string[] _methods = { "DELETE", "HEAD", "PUT" };
   4:      const string _header = "X-HTTP-Method-Override";
   5:   
   6:      protected override Task<HttpResponseMessage> SendAsync(
   7:          HttpRequestMessage request, CancellationToken cancellationToken)
   8:      {
   9:          // Check for HTTP POST with the X-HTTP-Method-Override header.
  10:          if (request.Method == HttpMethod.Post && request.Headers.Contains(_header))
  11:          {
  12:              // Check if the header value is in our methods list.
  13:              var method = request.Headers.GetValues(_header).FirstOrDefault();
  14:              if (_methods.Contains(method, StringComparer.InvariantCultureIgnoreCase))
  15:              {
  16:                  // Change the request method.
  17:                  request.Method = new HttpMethod(method);
  18:              }
  19:          }
  20:          return base.SendAsync(request, cancellationToken);
  21:      }
  22:  }

In the SendAsync method, the handler checks whether the request message is a POST request, and whether it contains the X-HTTP-Method-Override header. If so, it validates the header value, and then modifies the request method. Finally, the handler calls base.SendAsync to pass the message to the next handler.

When the request reaches the HttpControllerDispatcher class, HttpControllerDispatcher will route the request based on the updated request method.

Example: Adding a Custom Response Header

Here is a message handler that adds a custom header to every response message:

[!code-csharpMain]

   1:  // .Net 4.5
   2:  public class CustomHeaderHandler : DelegatingHandler
   3:  {
   4:      async protected override Task<HttpResponseMessage> SendAsync(
   5:              HttpRequestMessage request, CancellationToken cancellationToken)
   6:      {
   7:          HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
   8:          response.Headers.Add("X-Custom-Header", "This is my custom header.");
   9:          return response;
  10:      }
  11:  }

First, the handler calls base.SendAsync to pass the request to the inner message handler. The inner handler returns a response message, but it does so asynchronously using a Task<T> object. The response message is not available until base.SendAsync completes asynchronously.

This example uses the await keyword to perform work asynchronously after SendAsync completes. If you are targeting .NET Framework 4.0, use the Task<T>.ContinueWith method:

[!code-csharpMain]

   1:  public class CustomHeaderHandler : DelegatingHandler
   2:  {
   3:      protected override Task<HttpResponseMessage> SendAsync(
   4:          HttpRequestMessage request, CancellationToken cancellationToken)
   5:      {
   6:          return base.SendAsync(request, cancellationToken).ContinueWith(
   7:              (task) =>
   8:              {
   9:                  HttpResponseMessage response = task.Result;
  10:                  response.Headers.Add("X-Custom-Header", "This is my custom header.");
  11:                  return response;
  12:              }
  13:          );
  14:      }
  15:  }

Example: Checking for an API Key

Some web services require clients to include an API key in their request. The following example shows how a message handler can check requests for a valid API key:

[!code-csharpMain]

   1:  public class ApiKeyHandler : DelegatingHandler
   2:  {
   3:      public string Key { get; set; }
   4:   
   5:      public ApiKeyHandler(string key)
   6:      {
   7:          this.Key = key;
   8:      }
   9:   
  10:      protected override Task<HttpResponseMessage> SendAsync(
  11:          HttpRequestMessage request, CancellationToken cancellationToken)
  12:      {
  13:          if (!ValidateKey(request))
  14:          {
  15:              var response = new HttpResponseMessage(HttpStatusCode.Forbidden);
  16:              var tsc = new TaskCompletionSource<HttpResponseMessage>();
  17:              tsc.SetResult(response);    
  18:              return tsc.Task;
  19:          }
  20:          return base.SendAsync(request, cancellationToken);
  21:      }
  22:   
  23:      private bool ValidateKey(HttpRequestMessage message)
  24:      {
  25:          var query = message.RequestUri.ParseQueryString();
  26:          string key = query["key"];
  27:          return (key == Key);
  28:      }
  29:  }

This handler looks for the API key in the URI query string. (For this example, we assume that the key is a static string. A real implementation would probably use more complex validation.) If the query string contains the key, the handler passes the request to the inner handler.

If the request does not have a valid key, the handler creates a response message with status 403, Forbidden. In this case, the handler does not call base.SendAsync, so the inner handler never receives the request, nor does the controller. Therefore, the controller can assume that all incoming requests have a valid API key.

[!NOTE] If the API key applies only to certain controller actions, consider using an action filter instead of a message handler. Action filters run after URI routing is performed.

Per-Route Message Handlers

Handlers in the HttpConfiguration.MessageHandlers collection apply globally.

Alternatively, you can add a message handler to a specific route when you define the route:

[!code-csharpMain]

   1:  public static class WebApiConfig
   2:  {
   3:      public static void Register(HttpConfiguration config)
   4:      {
   5:          config.Routes.MapHttpRoute(
   6:              name: "Route1",
   7:              routeTemplate: "api/{controller}/{id}",
   8:              defaults: new { id = RouteParameter.Optional }
   9:          );
  10:   
  11:          config.Routes.MapHttpRoute(
  12:              name: "Route2",
  13:              routeTemplate: "api2/{controller}/{id}",
  14:              defaults: new { id = RouteParameter.Optional },
  15:              constraints: null,
  16:              handler: new MessageHandler2()  // per-route message handler
  17:          );
  18:   
  19:          config.MessageHandlers.Add(new MessageHandler1());  // global message handler
  20:      }
  21:  }

In this example, if the request URI matches “Route2”, the request is dispatched to MessageHandler2. The following diagram shows the pipeline for these two routes:

Notice that MessageHandler2 replaces the default HttpControllerDispatcher. In this example, MessageHandler2 creates the response, and requests that match “Route2” never go to a controller. This lets you replace the entire Web API controller mechanism with your own custom endpoint.

Alternatively, a per-route message handler can delegate to HttpControllerDispatcher, which then dispatches to a controller.

The following code shows how to configure this route:

[!code-csharpMain]

   1:  // List of delegating handlers.
   2:  DelegatingHandler[] handlers = new DelegatingHandler[] {
   3:      new MessageHandler3()
   4:  };
   5:   
   6:  // Create a message handler chain with an end-point.
   7:  var routeHandlers = HttpClientFactory.CreatePipeline(
   8:      new HttpControllerDispatcher(config), handlers);
   9:   
  10:  config.Routes.MapHttpRoute(
  11:      name: "Route2",
  12:      routeTemplate: "api2/{controller}/{id}",
  13:      defaults: new { id = RouteParameter.Optional },
  14:      constraints: null,
  15:      handler: routeHandlers
  16:  );



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/advanced/http-message-handlers.htm
< THANKS ME>