Message Interceptor in Web API

Track the pipeline process, wherein we can also validate or intercept the incoming API request. Microsoft had given us some of classes using that we can override the API Pipeline. In this example, I will implement DelegatingHandler

Here just creating a class SecurityMessageHandlerwhich is inherited fromDelegatingHandler



 Class Declaration

public class SecurityMessageHandler:DelegatingHandler
    {
    
        public SecurityMessageHandler()
        {
          
        }
       
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IEnumerable<string> headerValues;
            var tokenHeader = string.Empty;
            if (request.Headers.TryGetValues("Authorization", out headerValues))
            {
                tokenHeader = headerValues.FirstOrDefault();
            }

            if (!request.RequestUri.AbsolutePath.StartsWith("/api/"))
            {
                return await base.SendAsync(request, cancellationToken);
            }
         
            if (string.IsNullOrWhiteSpace(tokenHeader))
            {
                if (request.RequestUri.AbsolutePath.Contains("api/auth/"))
                {
                    return await base.SendAsync(request, cancellationToken);
                }
                else
                {
                    return await SendError("Wrong API Key", HttpStatusCode.Forbidden);
                }
            }

          
            return await base.SendAsync(request, cancellationToken);
        }

        private Task<HttpResponseMessage> SendError(string error, HttpStatusCode code)
        {
            var response = new HttpResponseMessage();
            response.Content = new StringContent(error);
            response.StatusCode = code;

            return Task<HttpResponseMessage>.Factory.StartNew(() => response);
        }

    }


Register the Handler
In given file location



app_start\webapiconfig.cs

  config.MessageHandlers.Add(new SecurityMessageHandler());


Now under the module “SendAsync

We can track or validate the incoming API with different process

if (!request.RequestUri.AbsolutePath.StartsWith("/api/"))
   {
     return await base.SendAsync(request, cancellationToken);
   }


Earlier we were using

base.SendAsync(request, cancellationToken).ContinueWith( (task) => 
                {
                     var response = task.Result;
                     response.Headers.Add("X-Custom-Header", "Custom-Header.");
                     return response;
                     } );


Note:  .ContinueWith from C#5 onwards, eased with using “async” and “await” see in above code



   


Message Interceptor in Web API Reviewed by Rupesh on 21:50 Rating: 5

No comments:

All Rights Reserved by Technology from Developers Eye © 2014 - 2015
Powered By Blogger, Designed by Aadics
Disclaimers:: The information provided within this blogsite is for general informational purposes only. While we try to keep the information up-to-date and correct, there are no representations or warranties, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the information, products, services, or related graphics contained in this blogsite for any purpose.The author does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.

Contact Form

Name

Email *

Message *

Powered by Blogger.