Working With Header in HttpHandler

This is the "HttpHandler and HttpModule in real scenerios" article series. As the name suggests, in this series we will understand a few real scenarios where we can use HttpHandler and HttpModule. In our previous three articles we have learned how to implement various HttpHandlers in our ASP.NET application. You can read them here.

In this article we will learn to work with a header in a HTTP request and response message. We know that, generally each HTTP message has two parts. One is the header part and the other is the body part. The header part contains certain information that helps both the web server and the client to process each HTTP request and response. In this article we will learn how to capture and set header information within HttpHandler.
 
Get Header value in HttpHandler

In this example we will read a specified header value of a HTTP request sent from the client part. If the header message is present in the HTTP request then we will return the specifeid message to the client. Have a look at the following example.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. namespace WebApp  
  9. {  
  10.     public class HeaderHandler : IHttpHandler  
  11.     {  
  12.         public void ProcessRequest(HttpContext context)  
  13.         {  
  14.             string []header = context.Request.Headers.AllKeys;  
  15.             if (!header.Contains("name"))  
  16.             {  
  17.                 context.Response.ContentType = "text/plain";  
  18.                 context.Response.Write("Please send name in request header");  
  19.             }  
  20.             else  
  21.             {  
  22.                 string name = context.Request.Headers.Get("name");  
  23.                 context.Response.ContentType = "text/plain";  
  24.                 context.Response.Write("Hi " + name + "! Thanks to send name in HTTP header");  
  25.             }  
  26.         }  
  27.         public bool IsReusable  
  28.         {  
  29.             get  
  30.             {  
  31.                 return false;  
  32.             }  
  33.         }  
  34.     }  
  35. } 

The example is pretty simple to understand at a glance. Within HttpHandler we are fetching all key values of the Header set that was set to the HTTP request. Then we are checking whether the "name" header is present or not in the request. If present then we are returning our custom message to the client.

Now, we will register the HttpHandler to the HTTP popeline. Just add the following code to your web.config file.    

  1. <system.webServer>  
  2.     <handlers>  
  3.        <add name="myImageHandler" verb="*" path="*.aspx" type="WebApp.HeaderHandler"/>  
  4.     </handlers>  
  5. </system.webServer> 

We will now use Fiddler to make a HTTP request to the application. Please don't forget to set the name header in the HTTP request (we are not seeing the header part in the following screen).

In this trial I have set Name:sourav in the current HTTP request, so that we are getting this welcome message.

Header value in HttpHandler

Now, if we do not set the name header in the HTTP request then we will get the following output.

Header in HTTP Request

Get Data in Request format

This is another possible scenario where we can use HttpHandler. Data formation at runtime is a very common task in modern software applications. In this example, our HttpHandler will generate data depending on the message type.

If the client request for data is in JSON format then it will produce a JSON format and if the client demands the data in XML format then it can do that.

This is the implementation of our HttpHandler.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Xml.Linq;  
  9. using Newtonsoft.Json;  
  10. namespace WebApp  
  11. {  
  12.     public class HeaderHandler : IHttpHandler  
  13.     {  
  14.         public List<string> name = new List<string>();  
  15.         public HeaderHandler()  
  16.         {  
  17.             name.Add("Sourav");  
  18.             name.Add("Ram");  
  19.             name.Add("Shyam");  
  20.         }  
  21.         public void ProcessRequest(HttpContext context)  
  22.         {  
  23.             string []header = context.Request.Headers.AllKeys;  
  24.             if (header.Contains("Content-Type"))  
  25.             {  
  26.                 if (context.Request.Headers.Get("Content-Type") == "application/json")  
  27.                 {  
  28.                     //Request for JSON data  
  29.                     //TODO: Return JSON data from here from storage  
  30.                     context.Response.ContentType = "text/plain";  
  31.                     context.Response.Write(JsonConvert.SerializeObject(name));  
  32.                 }  
  33.                 else if (context.Request.Headers.Get("Content-Type") == "application/xml")  
  34.                 {  
  35.                     //Request for XML data  
  36.                     //TODO: Return XML data from here from storage  
  37.                     context.Response.ContentType = "text/plain";  
  38.                     XElement xmlElements = new XElement("name", name.Select(i => new XElement("branch", i)));  
  39.                     context.Response.Write(xmlElements);  
  40.                 }  
  41.                 else  
  42.                 {  
  43.                     context.Response.ContentType = "text/plain";  
  44.                     context.Response.Write("requested unknown format");  
  45.                 }  
  46.             }  
  47.         }  
  48.         public bool IsReusable  
  49.         {  
  50.             get  
  51.             {  
  52.                 return false;  
  53.             }  
  54.         }  
  55.     }  
  56. }

The registration process of this HttpHandler is the same as in the previous example, so that we are skipping this part.

Let's see how it will work in real time. In our first trial we have set the Content-type header to "application/xml" and that's why we are getting data in XML format.

Data in Request format

In this example we will set the Content-type header to JSON so we are getting data in JSON format.
 
JSON format

Ok, it's really better to get the data depending on the demand (if you are a MVC Web API developer then you might not have fun with this example, Ha..Ha..)

Ok, in our previous two examples we learned how to read a header value in HttpHandler. But the interesting part is, it is possible to do more than just read. We can set the header value also in a Response HTTP message. In this example we will learn how to set the header information in the response message.

Set header information in HttpResponse

In this example we will set a "custom" header (yes, custom is the header name) associated with the HttpResponse message. Try to understand the following example.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Drawing;  
  4. using System.Drawing.Imaging;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Web;  
  8. using System.Xml.Linq;  
  9. using Newtonsoft.Json;  
  10. namespace WebApp  
  11. {  
  12.     public class HeaderHandler : IHttpHandler  
  13.     {  
  14.         public List<string> name = new List<string>();  
  15.         public HeaderHandler()  
  16.         {  
  17.             name.Add("Sourav");  
  18.             name.Add("Ram");  
  19.             name.Add("Shyam");  
  20.         }  
  21.         public void ProcessRequest(HttpContext context)  
  22.         {  
  23.                context.Response.ContentType = "text/plain";  
  24.                context.Response.AddHeader("custom","This is custom header, please ignore it");  
  25.                context.Response.Write("Please Check header");  
  26.         }  
  27.         public bool IsReusable  
  28.         {  
  29.             get  
  30.             {  
  31.                 return false;  
  32.             }  
  33.         }  
  34.     }  
  35. } 

Now , when we are getting the HTTP response message, in the header part we are getting our custom header.

HTTP Response Message

Conclusion

In this example we have worked with headers in HttpHander in request and response messages. I hope you have obtained some real time scenario/ideas to use HttpHandler in ASP.NET applications.


Similar Articles