pavanarya – Pavan Kumar Aryasomayajulu

Contact Email : pavan.aryasomayajulu@gmail.com

HttpHandlers in C#

with 2 comments

Hi,
In this post i want to write about HttpHandlers in C#.

An overview on how web requests are handled and executed by IIS

Generally whenever we request for a resource like localhost\MyWebApp\Firstpage.aspx

1. First of all the request reaches IIS and it identifies that this particular request should be handled by the .Net framework.

2. Next the request is handled by the worker process.

3. Next the worker process identifies the appropriate class that should handle this request.

This particular class is nothing but a HttpHandler. Now let us go through this.

HttpHandler

A HttpHandler is nothing but a class that handles incoming requests. Asp.Net framework identifies the appropriate handler based on the file extension in the request url.

IHttpHandler
A HttpHandler is nothing but a class that implements IHttpHandler interface. IHttpHandler has two methods.

public interface IHttpHandler
{
    // Methods
    void ProcessRequest(HttpContext context);

    // Properties
    bool IsReusable { get; }
}

So any class implementing IHttphandler interface should define these two (ProcessRequest method and IsReusable property).

ProcessRequest should have the key logic to handle the http request. This is the method that is executed whenever a request comes.

Creating a class that implements IHttpHandler

This handler is called whenever a file ending in .pavan is requested. A file with that extension does not need to exist.

using System.Web;
public class MyHandler : IHttpHandler
{
    public MyHandler()
    {
    }
    public void ProcessRequest(HttpContext context)
    {
        System.Diagnostics.Debugger.Break();
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
       
        Response.Write("<html>");
        Response.Write("<body>");
        Response.Write("<h1>Hi This is my first httphandler.</h1>");
        Response.Write("</body>");
        Response.Write("</html>");
    }
    public bool IsReusable
    {
        get { return false; }
    }
}

IsReusable is used to specify whether we want to enable pooling or not. If set to true the handler is placed in the memory and it is pooled.

In the processRequest function i am just writing the text “Hi this is my first httphandler” as a response to the request we got.

So we are done with the creation of Httphandler.

Now you might be having a question. How does IIS know about this handler. How this particular request localhost\MySample\Test.pavan is going to be redirected to our handler by IIS.

Now let me answer these questions.

1. We are supposed to configure the web.config file

Configuring Web.config For IIS7

i. There is a tag called Add, replace that with this tag or if not there add this tag.

        <add verb="*" path="*.pavan" type="MyHandler" />

Here verb corresponds to the http protocol that our handler supports like ‘GET’,’POST’ etc

Path—The extension this particular handler should take care

Type—The class that handles the request. In our case MyHandler (This should be qualified name).

Mapping File extension to handlers in IIS7.0

1. Go to Command prompt and click Inetmgr.

2. create a website and host our website that contains Httphandler. I am naming my app as Test

Click on the HttpHandlerMapping in the below image

Now we can list of handler mappings in this image

Now let me click on .aspx and see to which handler that is actually pointing
Yes it is pointing to aspnet_isapi.dll. This is not a c# class but this will inturn process it and assign the aspx request to appropriate handler

Now let us click on “Add Managed handler”

Fill the fields with appropriate values.
Requestpath—file extension to be handled.
Type—name of the class
Name—Name of the handler.

Now click on save.

Now go back to our solution and we can find that web.config is changed and few more tags were added to it

<system.webServer>
        <handlers accessPolicy="Read, Execute, Script">
            <remove name="Test" />
            <add name="MyHandler" path="*.pavan" verb="GET,HEAD,POST,DEBUG" type="MyHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode" />
        </handlers>
    </system.webServer>

These tags we added automatically when we add mappings in iis.

The complete web.config file

<configuration>
    <system.web>
        <compilation debug="true" />
      <httpHandlers>
        <add verb="*" path="*.pavan" type="MyHandler" />
      </httpHandlers>
    </system.web>
    <system.webServer>
        <handlers accessPolicy="Read, Execute, Script">
            <remove name="Test" />
            <add name="MyHandler" path="*.pavan" verb="GET,HEAD,POST,DEBUG" type="MyHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode" />
        </handlers>
    </system.webServer>

</configuration>

Testing our First Httphandler

Type this url in the browser “http://localhost:6192/samplewebservice/test.pavan&#8221; and we can see the result on the screen.

Debugging Httphandler

if we want to debug the httphandler in our local machines , we can add this line

System.Diagnostics.Debugger.Break();

Complete HttpHandler class code

using System.Web;
public class MyHandler : IHttpHandler
{
    public MyHandler()
    {
    }
    public void ProcessRequest(HttpContext context)
    {
        System.Diagnostics.Debugger.Break();
        HttpRequest Request = context.Request;
        HttpResponse Response = context.Response;
        // This handler is called whenever a file ending 
        // in .sample is requested. A file with that extension
        // does not need to exist.
        Response.Write("<html>");
        Response.Write("<body>");
        Response.Write("<h1>Hello from a synchronous custom HTTP handler.</h1>");
        Response.Write("</body>");
        Response.Write("</html>");
    }
    public bool IsReusable
    {
        // To enable pooling, return true here.
        // This keeps the handler in memory.
        get { return false; }
    }
}

In my next post i want to write about “How .asmx file request were handled”.

Thanks,
pavan

Written by pavanarya

August 13, 2012 at 10:11 pm

Posted in Asp.net, HttpHandler

2 Responses

Subscribe to comments with RSS.

  1. Great info, very helpful. Small correction: “i. Add a tag called , inside that place this tag” should be “i. Add a tag called , inside that place this tag:”

    Marty

    August 18, 2012 at 6:22 pm

  2. […] HttpHandlers in C# – Pavanarya […]


Leave a comment