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.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Web;

 

namespace WebApp

{

    public class HeaderHandler : IHttpHandler

    {

        public void ProcessRequest(HttpContext context)

        {

            string []header = context.Request.Headers.AllKeys;

            if (!header.Contains("name"))

            {

                context.Response.ContentType = "text/plain";

                context.Response.Write("Please send name in request header");

            }

            else

            {

                string name = context.Request.Headers.Get("name");

                context.Response.ContentType = "text/plain";

                context.Response.Write("Hi " + name + "! Thanks to send name in HTTP header");

            }

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

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.    

</system.webServer>

    <handlers>

       <add name="myImageHandler" verb="*" path="*.aspx" type="WebApp.HeaderHandler"/>

    </handlers>

</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.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Web;

using System.Xml.Linq;

using Newtonsoft.Json;

namespace WebApp

{

    public class HeaderHandler : IHttpHandler

    {

        public List<string> name = new List<string>();

        public HeaderHandler()

        {

            name.Add("Sourav");

            name.Add("Ram");

            name.Add("Shyam");

        }

 

        public void ProcessRequest(HttpContext context)

        {

            string []header = context.Request.Headers.AllKeys;

            if (header.Contains("Content-Type"))

            {

                if (context.Request.Headers.Get("Content-Type") == "application/json")

                {

                    //Request for JSON data

                    //TODO: Return JSON data from here from storage

                    context.Response.ContentType = "text/plain";

                    context.Response.Write(JsonConvert.SerializeObject(name));

                }

                else if (context.Request.Headers.Get("Content-Type") == "application/xml")

                {

                    //Request for XML data

                    //TODO: Return XML data from here from storage

                    context.Response.ContentType = "text/plain";

                    XElement xmlElements = new XElement("name", name.Select(i => new XElement("branch", i)));

                    context.Response.Write(xmlElements);

                }

                else

                {

                    context.Response.ContentType = "text/plain";

                    context.Response.Write("requested unknown format");

                }

            }

           

        }

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

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.

using System;

using System.Collections.Generic;

using System.Drawing;

using System.Drawing.Imaging;

using System.IO;

using System.Linq;

using System.Web;

using System.Xml.Linq;

using Newtonsoft.Json;

namespace WebApp

{

    public class HeaderHandler : IHttpHandler

    {

        public List<string> name = new List<string>();

        public HeaderHandler()

        {

            name.Add("Sourav");

            name.Add("Ram");

            name.Add("Shyam");

        }

 

        public void ProcessRequest(HttpContext context)

        {

               context.Response.ContentType = "text/plain";

               context.Response.AddHeader("custom","This is custom header, please ignore it");

               context.Response.Write("Please Check header");

        }

 

        public bool IsReusable

        {

            get

            {

                return false;

            }

        }

    }

}

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.

Up Next
    Ebook Download
    View all
    Learn
    View all