How to add custom message handlers to the pipeline in Asp.Net webAPI C#?

CsharpServer Side ProgrammingProgramming

To create a custom Server-Side HTTP Message Handler in ASP.NET Web API, we need to create a class that must be derived from the System.Net.Http.DelegatingHandler.

Step 1 −

Create a controller and its corresponding action methods.

Example

using DemoWebApplication.Models;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
   public class StudentController : ApiController{
      List<Student> students = new List<Student>{
         new Student{
            Id = 1,
            Name = "Mark"
         },
         new Student{
            Id = 2,
            Name = "John"
         }
      };
      public IEnumerable<Student> Get(){
         return students;
      }
      public Student Get(int id){
         var studentForId = students.FirstOrDefault(x => x.Id == id);
         return studentForId;
      }
   }
}

Step 2 −

Create our own CutomerMessageHandler class.

Example

using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace DemoWebApplication{
   public class CustomMessageHandler : DelegatingHandler{
      protected async override Task<HttpResponseMessage>
      SendAsync(HttpRequestMessage request, CancellationToken cancellationToken){
         var response = new HttpResponseMessage(HttpStatusCode.OK){
            Content = new StringContent("Result through custom message handler..")
         };
         var taskCompletionSource = new
         TaskCompletionSource<HttpResponseMessage>();
         taskCompletionSource.SetResult(response);
         return await taskCompletionSource.Task;
      }
   }
}

We have declared the CustomMessageHandler class derived from DelegatingHandler and within that we have overriden the SendAsync() function.

When a HTTP request arrives CustomMessageHandler will execute and it will return one HTTP message on its own, without processing the HTTP request further. So ultimately we are preventing each and every HTTP request from reach its higher level.

Step 3 −

Now register the CustomMessageHandler in Global.asax class.

public class WebApiApplication : System.Web.HttpApplication{
   protected void Application_Start(){
      GlobalConfiguration.Configure(WebApiConfig.Register);
      GlobalConfiguration.Configuration.MessageHandlers.Add(new
      CustomMessageHandler());
   }
}

Step 4 −

Run the application and provide the Url.

From the above output we could see the message that we have set in our CustomMessageHandler class. So the HTTP message is not reaching the Get() action and before that it is returning to our CustomMessageHandler class.

raja
Published on 24-Sep-2020 15:50:40
Advertisements