Thursday, February 7, 2013

HttpHandler in Asp .Net

An ASP.NET HTTP handler is basically a process that runs in response to a request made to an ASP.NET Web application. The most common handler is the ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. (Wikipedia)

I am going to create an Http Handler which will serve an image in response to a request like Shalvin.img.



public class MyHandler : IHttpHandler
{
        public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";
        context.Response.WriteFile("Session.jpg");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

For directing the application to use this handler when i request Shalvin.img I have to add a few sections in web.config.


<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>

    <httpHandlers>
      <add verb="*" path="Shalvin.img" type="MyHandler, App_Code"/>
    </httpHandlers>
    
  </system.web>
  
  <system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>

  <handlers>
    <add name="ImageHandler" verb="*" path="Shalvin.img" type="MyHandler, App_code" />
  </handlers>
  </system.webServer>
  
</configuration>