Custom Messsage Handler in SelfHost WebApi Application

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

Task<HttpResponseMessage> SendAsync(
    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.

Source Code

class Program
    {
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:5004");
            config.Routes.MapHttpRoute("API Default",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional }
                );
            config.MessageHandlers.Add(new CustomMessageHandler());
            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Please Enter to Quit");
                Console.ReadKey();

            }
        }
    }
 public class CustomMessageHandler : DelegatingHandler
    {
        protected async override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);
            Console.WriteLine("-------Request URL ----------- "); 
            Console.WriteLine(request.RequestUri);
            Console.WriteLine("-------Response------");
            Console.WriteLine(response);
            
            return response;
        }
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s