Monday, March 1, 2010

ASP.net - Http handlers - implementing IHttpHandler



Implementing a generic HTTP handler has its own limitations. To give more power to handle request in any URL we can create our own HTTP handlers using the interface IHttpHandler. This interface defines the contract that ASP.NET implements to synchronously process HTTP Web requests using custom HTTP handlers.

You can create HTTP handler in any of the .net language which can run in the framework (any CLS compliant language).
In the following example I have used C#

public class ImageHandlerNew :IHttpHandler
    {
        const string connectionStringName = "Images";

        public void ProcessRequest(HttpContext context)
        {
           

        }

        public bool IsReusable
        {
            get { return true; }
        }

    }

In this example the most important function is ProcessRequest which handles the incoming request from browser, process it and sends back the response. This function takes the current running context as parameter. This context enables has all the runtime objects & context information of ASPX execution thread.
As mentioned in http://thetechjungle.blogspot.com/2010/02/aspnet-http-handlers-generic-hander.html , The IsReusable property indicates whether the same handler can be reused over multiple requests. 

You can add a lot of different functionalities like generating the PDF, excel files or retrieving the stock quotes in ProcessRequest function (when client requests for a specific resource). For testing you can use the following function which retrieves the image file stored in SQL server database.

  public void ProcessRequest(HttpContext context)
        {
            context.Response.Buffer = false;

            string filename = VirtualPathUtility.GetFileName(context.Request.Path);

            string connstring = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;

            SqlConnection con = new SqlConnection(connstring);
            SqlCommand cmd = new SqlCommand("SELECT Image FROM Images WHERE FileName=@FileName", con);
            cmd.Parameters.AddWithValue("@FileName", filename);

            using (con)
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                if (reader.Read())
                {
                    int bufferSize = 8040;
                    byte[] chunk = new byte[bufferSize];
                    long retcount;
                    long startindex = 0;
                    retcount = reader.GetBytes(0, startindex, chunk, 0, bufferSize);
                    while (retcount == bufferSize)
                    {
                        context.Response.BinaryWrite(chunk);

                        startindex += bufferSize;
                        retcount = reader.GetBytes(0, startindex, chunk, 0, bufferSize);
                    }

                    byte[] actualchunk = new byte[retcount - 1];
                    Buffer.BlockCopy(chunk, 0, actualchunk, 0,(int) retcount-1);
                    context.Response.BinaryWrite(actualchunk);
                }
            }

        }

After adding thie CS file in your application add the following in web.config

<httpHandlers>
              <add verb="*" path="*.gif" validate="false" type="AspNet.ImageHandlerNew"/>
              <add verb="*" path="*.jpg" validate="false" type="AspNet.ImageHandlerNew"/>
              <add verb="*" path="*.jpeg" validate="false" type="AspNet.ImageHandlerNew"/>
      httpHandlers>

  • path: Enables you to specify the path associated with the handler. You can use wildcards in the path expression.
  • verb:Enables you to specify the HTTP verbs, such as GET or POST, associated with the handler. You can specify multiple verbs in a comma-separated list. You can represent any verb with the * wildcard.
  • type : Enables you to specify the name of the class that implements the handler.
  • validate:Enables you to specify whether the handler is loaded during application startup. When true, the handler is loaded at startup. When false, the handler is not loaded until a request associated with the handler is made. This second option can improve your application’s performance.

How to execute this Handler?
Remember once you create this handler all the requests for .gif,.jpg & .jpeg resources will be handled by this. So if the corresponding data is not available in database this code will not display anything. You don’t have to add any special code in your aspx or associated class files, ASPNET/IIS runtime will automatically redirect the corresponding resource request to this class/dll.


Using this you can create your own extensions & produce the output !!!!
Post a Comment