X-HTTP-Method-Override For Rest Web API

Sometimes, some clients cannot send certain HTTP request types, such as PUT or DELETE. Also, most times, some production environments are not configured to accept some request types, such as PUT, PATCH e.t.c.

One of the tricks around this is to clients send  POST request and set the X-HTTP-Method-Override header to the desired method. Then create a custom message handler that overrides the original request method.

Create custom message handler that adds support for X-HTTP-Method-Override like so:

using System;  
using System.Linq;  
using System.Net.Http;  
using System.Threading;  
using System.Threading.Tasks;  
namespace MessagehandlerWithWebAPI.Filters  
  public class MethodOverrideHandler: DelegatingHandler  
     readonly string[] acceptedOverrideMethods = { "PUT", "DELETE", "PATCH" };  
     const string headerKey = "X-HTTP-Method-Override";  
     protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)  
       if(request.Method==HttpMethod.Post && request.Headers.Contains(headerKey))  
         var overrideMethod = request.Headers.GetValues(headerKey).FirstOrDefault();  
         if (overrideMethod != null && acceptedOverrideMethods.Contains(overrideMethod, StringComparer.InvariantCultureIgnoreCase))  
           request.Method = new HttpMethod(overrideMethod);  
       return base.SendAsync(request, cancellationToken);  

From above,
  • We declare an array of  methods clients can override.
  • In the SendAsync, the handler  checks if is a POST request, and also, if the header contains the X-HTTP-Method-Override.
  • The header value is validated and then modifies the request method.
  • The handler then calls base.SendAsync  to pass the request message to the next handler in the pipeline.
Register the custom handler in WebApiConfig class like so:

 using MessagehandlerWithWebAPI.Filters;  
 using System.Web.Http;  
 namespace MessagehandlerWithWebAPI  
   public static class WebApiConfig  
     public static void Register(HttpConfiguration config)  
       // Web API configuration and services  
        config.MessageHandlers.Add(new MethodOverrideHandler());  
        // Web API routes  
          name: "DefaultApi",  
          routeTemplate: "api/{controller}/{id}",  
          defaults: new { id = RouteParameter.Optional }  

When the request reaches the HttpContollerDispatcher handler in the pipeline, it will route the request appropriately based on the updated request method.

I hope the article is helpful.

Your comments and feedback will be greatly appreciated.

Than you for your time.
X-HTTP-Method-Override For Rest Web API X-HTTP-Method-Override For Rest Web API Reviewed by Akintunde Toba on February 03, 2020 Rating: 5

No comments:

Home Ads

Powered by Blogger.