Custom Message Handler in Web API




What is Message Handler?

Message Handler is a class that derives from HttpMessageHandler class, receives HTTP request and returns HTTP response.
Message handlers are chain of classes in a pipeline, sitting next to the process of HTTP request and response. The first handler in a pipeline receives an HTTP request, process it and gives the request to the next handler or creates a response that goes back up the chain.

 


Message Handlers can be used on both the server-side and client side. But in this article, we will only consider server-side handlers so as to keep things simple.

Server Side Message Handlers
 
Built-in message handlers in  Web API pipeline:
  • HttpServer: receives the request from host.
  • HttpRoutingDispatcher: channels the request based on route.
  • HttpControllerDispatcher: send the request to the appropriate Controller.
Custom handlers can be added to the pipeline to:
  • Validate requests before they reach the controller
  • Modify request headers
  • Process request message
  • Process response
  • Add response header to responses



Create Custom Message Handler

Create a class that derives from System.Net.Http.DelegatingHandler, then override the SendAsync method like so:

1:  using System.Net.Http;  
2:  using System.Threading;  
3:  using System.Threading.Tasks;  
4:  namespace MessagehandlerWithWebAPI.Filters  
5:  {  
6:    public class RequestFilterHandler:DelegatingHandler  
7:    {  
8:      protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
9:      {  
10:        return base.SendAsync(request, cancellationToken);  
11:      }  
12:    }  
13:  }  

Custom Message handler implementation generally does the following
  1. Receives request message
  2. Process the request message
  3. Send the request to the inner handler by calling base.SendAsync
  4. Receives response message from the inner handler
  5. Process the response
  6. Return the response message to the caller
Custom handler can directly create response by skipping the inner handlers in the pipeline. This can be achieved by creating response without calling base.SendAsync.

Add Custom Handler to the Pipeline

Custom handlers can be added to the pipeline by the following:
  1. Inside the WebApiConfig class
  2. In Global.asax class
Add Handlers in WebApiConfig class like so:

1:  using MessagehandlerWithWebAPI.Filters;  
2:  using System.Web.Http;  
3:  namespace MessagehandlerWithWebAPI  
4:  {  
5:    public static class WebApiConfig  
6:    {  
7:      public static void Register(HttpConfiguration config)  
8:      {  
9:        // Web API configuration and services  
10:        config.MessageHandlers.Add(new RequestFilterHandler());  
11:        //config.MessageHandlers.Add(new Handler2());  
12:        //config.MessageHandlers.Add(new Handler3());  
13:        // Web API routes  
14:        config.MapHttpAttributeRoutes();  
15:        config.Routes.MapHttpRoute(  
16:          name: "DefaultApi",  
17:          routeTemplate: "api/{controller}/{id}",  
18:          defaults: new { id = RouteParameter.Optional }  
19:        );  
20:      }  
21:    }  
22:  }  

Add custom handlers in Global.asax class like so:

1:  using MessagehandlerWithWebAPI.Filters;  
2:  using System.Web.Http;  
3:  using System.Web.Mvc;  
4:  using System.Web.Optimization;  
5:  using System.Web.Routing;  
6:  namespace MessagehandlerWithWebAPI  
7:  {  
8:    public class WebApiApplication : System.Web.HttpApplication  
9:    {  
10:      protected void Application_Start()  
11:      {  
12:        AreaRegistration.RegisterAllAreas();  
13:        GlobalConfiguration.Configure(WebApiConfig.Register);  
14:        GlobalConfiguration.Configuration.MessageHandlers.Add(new RequestFilterHandler());  
15:        //GlobalConfiguration.Configuration.MessageHandlers.Add(new Handler2());  
16:        //GlobalConfiguration.Configuration.MessageHandlers.Add(new Handler3());  
17:        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
18:        RouteConfig.RegisterRoutes(RouteTable.Routes);  
19:        BundleConfig.RegisterBundles(BundleTable.Bundles);  
20:      }  
21:    }  
22:  }  

The handlers are called in sequence they appeared. like so:
RequestFilterHandler  >>  Handler2  >> Handler3 

The response message travels in the other direction, hence the first handler in the pipeline is the last handler to receive  response message. like so:
RequestFilterHandler  <<  Handler2  << Handler3

Sample Project

In the sample project, we will create Web API that returns a list of names, then use custom message handler to validate API key.

Create web API with get method that returns list of names like so:
1:  using System.Collections.Generic;  
2:  using System.Web.Http;  
3:  namespace MessagehandlerWithWebAPI.Controllers  
4:  {  
5:    [RoutePrefix("api/v1")]  
6:    public class NamesController : ApiController  
7:    {  
8:      [HttpGet]  
9:      [Route("names")]  
10:      public IEnumerable<string> GetNames()  
11:      {  
12:        return new List<string>() { "Akin", "Mark","thurbarh"};  
13:      }  
14:    }  
15:  }  

Create a folder called filter, then add new class like so:

1:  using System.Net.Http;  
2:  using System.Threading;  
3:  using System.Threading.Tasks;  
4:  namespace MessagehandlerWithWebAPI.Filters  
5:  {  
6:    public class RequestFilterHandler:DelegatingHandler  
7:    {  
8:      protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
9:      {  
10:        return base.SendAsync(request, cancellationToken);  
11:      }  
12:    }  
13:  }  

Modify the RequestFilterHandler class to validate API key like so:

1:  using System.Net.Http;  
2:  using System.Threading;  
3:  using System.Threading.Tasks;  
4:  using System.Linq;  
5:  namespace MessagehandlerWithWebAPI.Filters  
6:  {  
7:    public class RequestFilterHandler:DelegatingHandler  
8:    {  
9:      protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
10:      {  
11:        if (!ValidateKey(request))  
12:        {  
13:          var res = request.CreateResponse(System.Net.HttpStatusCode.Forbidden,  
14:            new  
15:            {  
16:              error = true,  
17:              message = "Access Denied, Invalid request",  
18:            });  
19:          var tsk = new TaskCompletionSource<HttpResponseMessage>();  
20:          tsk.SetResult(res);  
21:          return tsk.Task;  
22:        }  
23:        return base.SendAsync(request, cancellationToken);  
24:      }  
25:      private bool ValidateKey(HttpRequestMessage request)  
26:      {  
27:        if (!request.Headers.Contains("X-AUTH-KEY")) return false;  
28:        return request.Headers.GetValues("X-AUTH-KEY").FirstOrDefault()=="QHU7V2K0=YWQ";  
29:      }  
30:    }  
31:  }  

Add the custom handler to the pipeline in Global.asax class like so:

1:  using MessagehandlerWithWebAPI.Filters;  
2:  using System.Web.Http;  
3:  using System.Web.Mvc;  
4:  using System.Web.Routing;  
5:  namespace MessagehandlerWithWebAPI  
6:  {  
7:    public class WebApiApplication : System.Web.HttpApplication  
8:    {  
9:      protected void Application_Start()  
10:      {  
11:        AreaRegistration.RegisterAllAreas();  
12:        GlobalConfiguration.Configure(WebApiConfig.Register);  
13:        GlobalConfiguration.Configuration.MessageHandlers.Add(new RequestFilterHandler());  
14:        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);  
15:        RouteConfig.RegisterRoutes(RouteTable.Routes);  
16:      }  
17:    }  
18:  }  

Build and run the application, use postman to invoke the GetNames() action.
You should have:


Add the API key to the request header and try again like so:

The source code of the sample project can be downloaded here

I hope the article is helpful, kindly leave comment in the comment section below.

Thank you for your time.

                                                                          X-HTTP-Method-Override For Rest Web API >>>
Custom Message Handler in Web API Custom Message Handler in Web API Reviewed by Akintunde Toba on February 03, 2020 Rating: 5

No comments:

Home Ads

Powered by Blogger.