Tutorials

HttpHandlers in .NET demystified

Sending
User Rating 5 (1 vote)

What is Http Handlers?
An ASP.NET HTTP handler is the process that runs in response to a request that is made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page handler.

HTTP handlers are of two types:

  • Synchronous HTTP Handlers: These handlers process the HTTP request in a synchronous manner and will return only when processing of the request for which it is called is complete.
  • Asynchronous HTTP Handlers: These handlers process the HTTP request in an asynchronous manner. It allows the user to make remote server calls to start an external process. This greatly improves performance as these handlers do not wait for the completion of external processes.

Built-In Http Handlers in ASP.Net

ASP.NET maps HTTP requests to HTTP handlers based on a file name extension. Each HTTP handler can process individual HTTP URLs or groups of URL extensions in an application. ASP.NET includes several built-in HTTP handlers, as listed in the following table.

 

Handler

Description

ASP.NET page handler (*.aspx)

The default HTTP handler for all ASP.NET pages

Web service handler (*.asmx)

The default HTTP handler for Web service pages created as .asmx files in ASP.NET.

Generic Web handler (*.ashx)

The default HTTP handler for all Web handlers that do not have a UI and that include the @ WebHandler directive.

Trace handler (trace.axd)

A handler that displays current page trace information.

 

What is Generic web  Handler?
A Generic Handler is like an ASP.NET page that contains a single method that renders content to the browser.
You can't add any controls declaratively to a Generic Handler. A Generic Handler doesn't support events such as the Page Load or Page PreRender events.

The .ashx file extension is usually reserved for custom handlers. Custom handlers created with the extension of .ashx gets automatically registered within IIS and ASP.NET. If an alternate file extension is used, then it is explicitly required to register the extension within IIS and ASP.NET (As will be seen in the Custom Handler example below).
The advantage of using an extension over .ashx is that multiple file extensions can be assigned to a single handler.

Implementation of Generic Web handler

HttpHandler optionGeneric Handler
Custom Http Handlers can be implemented by overriding either IHttpHandler interface to create a synchronous handler or the IHttpAsyncHandler interface to create an asynchronous handler. These interfaces require the implementation of the following:

Here in the above figure handler1.ashx.vb had implemented the interface IHttphandler . The interface IhttpHandler requires the implementation of the following.

  1. void ProcessRequest(HttpContext) : This method handles the actual processing for requests made.
  2. bool IsReusable {get;} : The IsReusable() indicates whether or not your handler instance can be re-used for subsequent requests.  In some cases, after processing the request your handler may be in an incorrect state to process another request, especially if you have stored data about the previous request in member variables.  Note that the runtime will never use the same instance of your handler to process two requests at the same time, even if its marked as reusable.  If your handler does not store any per-request state in member variables and can have its ProcessRequest function called as many times as needed, make this property return true to allow reuse.

 

The code present in the handler1.ashx.cs is :

public void ProcessRequest(HttpContext context)
        {
            System.IO.Stream strm = context.Request.InputStream;
 
            XmlDocument xdResp = new XmlDocument();
            xdResp.Load(strm);
            XmlNodeList m_nodelist;
            string ret = "";
            XmlNode m_node1;
 
        
 
            m_nodelist = xdResp.SelectNodes("/transaction-results");
            foreach (XmlNode m_node in m_nodelist)
            {
                if (m_node.HasChildNodes)
                {
                    for (int i = 0; i < m_node.ChildNodes.Count; i++)
                    {
                        m_node1 = m_node.ChildNodes.Item(i);
                        ret = ret + m_node1.Name.ToString() + " : " + m_node1.InnerText.ToString() + Environment.NewLine;
                      
                    }
                }
            }
            HttpResponse r = context.Response;
            r.Output.Write(ret);
        }
 
        public bool IsReusable
        {
            get
            {
                return true;
            }
}

Here In the method Process request we are receiving the request in the httpcontext object and after doing the desired operation we are writing the output to HttpResponse object . This HttpResponse object is send  to client who are using this handler .
Here I am doing url mapping of Default.aspx to Handler1.ashx so that whenever the page default.aspx page is requested the web handler handler1.ashx will process the coming request and give back the response .For doing urlmapping we have to add
   
<system.web>
      <urlMappings  enabled="true">
        <add url="~/Default.aspx" mappedUrl="~/Handler1.ashx"/>
      </urlMappings>
</system.web>
 

In the web.config inside the <system.web> tag of Testhandler web application in the current case .
So now our Handler is ready to process an xml and reply back some results .
 
Adding the Client

 Test handlers
Here I have added one Web application and named it as TestHandlers with a page testpage.aspx

The UI of Client Is show below:

Explorer bar UI Client page
 
It contains three text boxes and one button.
The first Text Box Contains the Input XML Which we are going to send to the specified handler. The address of the handler we are going to specify in the 2nd text Box as shown below. For getting the address of the handler first we have to do view in browser for default.aspx of Httphandler web application.

Address marked

The Same Address we are going to provide in the second text Box and on click of button click to see the handlers Response . The Response will get displayed in the third test box as shown in the below screen shots.

Response pageFinal Handler Response
 
The Code Written On click of button click to see Handlers Response is given Below :
 
protected void btnHandlers_Click(object sender, EventArgs e)
        {
            uri = txthttphandlers.Text.ToString();
            string strPost = txtInput.Text.ToString();
           
            txtHandlerOutput.Visible = true;
            txtHandlerOutput.Text = processresponse(strPost);
        }
 
        private string processresponse(string strPost)
        {
 
            byte[] reqBytes = new byte[strPost.Length];
            int i = 0;
            foreach (char c in strPost.ToCharArray())
            {
                reqBytes[i] = (byte)c;
                i++;
            }
            //System.Net.WebRequest postRequest = SendHTTPRequest(uri, reqBytes, false);
 
            HttpWebRequest postRequest = SendHTTPRequest(uri, reqBytes, false);
            HttpWebResponse webResponse = (HttpWebResponse)postRequest.GetResponse();
 
            System.IO.StreamReader streamReader = new System.IO.StreamReader(webResponse.GetResponseStream());
            string stringResult = streamReader.ReadToEnd();
 
            return stringResult;
         }
 
        private HttpWebRequest SendHTTPRequest(string url, byte[] reqBytes, bool useProxy)
        {
            HttpWebRequest postRequest = (HttpWebRequest)WebRequest.Create(uri);
            postRequest.Proxy = null;
            postRequest.UseDefaultCredentials = true;
            postRequest.Method = "POST";
            postRequest.ContentLength = reqBytes.Length;
            postRequest.ContentType = "text/xml";//"application/x-www-form-urlencoded";
            System.IO.Stream stream = postRequest.GetRequestStream();
            stream.Write(reqBytes, 0, reqBytes.Length);
            //stream.Close();
            return postRequest;
        }
 

 
For using HttpWebRequest and HttpWebResponse Object we have to use the namespace : using System.Net;
Also include these namespaces
using Microsoft.Http;
using Microsoft.ServiceModel.Web;
using Microsoft.ServiceModel.Web.SpecializedServices;
 
Handler vs. Web Pages
ASP.NET web forms inherit from the Page class. This provides them with many events and a very detailed initialization and event model. You don't need that for dynamic images, XML, or binary files.

Performance
ASHX files are less complex and they do not involve as many events. As you can imagine firing more than ten events each time a request is handled is a fair amount more expensive than only firing one event. Therefore, there will be some performance advantage to using ASHX files where possible.

When to choose Handlers?
If you have:

  • Simple HTML pages
  • ASP.NET custom controls
  • Simple dynamic pages
  • Binary Files
  • Dynamic Image Views
  • Performance-Critical web pages
  • XML Files
  • Minimal Web Pages

Share your Thoughts