HTTP Handlers in ASP

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 6

HTTP Handlers in ASP.

NET

The low level Request and Response API to service incoming Http requests are Http Handlers in Asp.Net. All
handlers implement the IHttpHandler interface, which is located in the System.Web namespace. Handlers are
somewhat analogous to Internet Server Application Programming Interface (ISAPI) extensions.

Methods in Http Handler

The following are the methods in Http Handlers.

Method Name Description


ProcessRequest Used to call Http Requests.
IsReusable To check the reusability of same instance handler with a new request of same type.

Configuring HTTP Handlers

The configuration section handler is responsible for mapping incoming URLs to the IHttpHandler or
IHttpHandlerFactory class. It can be declared at the computer, site, or application level. Subdirectories inherit
these settings. Administrators use the tag directive to configure the section. directives are interpreted and
processed in a top-down sequential order. Use the following syntax for the section handler:

<httpHandlers>
<add verb="[verb list]" path="[path/wildcard]" type="[COM+ Class], [Assembly]"
validate="[true/false]" />
<remove verb="[verb list]" path="[path/wildcard]" />
<clear />
</httpHandlers>

Creating HTTP Handlers

To create an HTTP handler, you must implement the IHttpHandler interface. The IHttpHandler interface has
one method and one property with the following signatures:

void ProcessRequest(HttpContext); bool IsReusable {get;}

Customized Http Handler

By customizing http handlers, new functionalities can be added to Web Server. Files with new extensions like
.text for a text file can be handled by Web Server by using http handlers. The future of customization can lead
to hosting .jsp pages in IIS by finding adequate ISAPI extensions. The following steps are involved to create
customized http handler:

1. Create a C# class library as “Examplehandler”


2. Name class as “Handlerclass.cs”

using System;
using System.Web;
using System.Web.SessionState;
namespace ExampleHandler
{
public class Handlerclass : IHttpHandler
{
public Handlerclass()
{
}
#region Implementation of IHttpHandler
public void ProcessRequest(System.Web.HttpContext context)
{
HttpResponse objResponse = context.Response ;
HttpSessionState objSession = context.Session ;
objResponse.Write("<html><body><h1>Hello World from Handler") ;
objResponse.Write("</body></html>") ;
}

public bool IsReusable


{
Get { return true; }
} #endregion
}
}

Compile it and place it in the bin directory of TestApp project.

Step 2

Register this handler by adding the following text in the web.config file:
<httpHandlers>
<add verb="*" path="*.text" type="ExampleHandler.Handlerclass, ExampleHandler "/>
</httpHandlers>

Step 3

Go to Internet Information Services and select Default Web Site. Right Click and Select Properties. Select
Home Directory and click on Configuration. The Following Screen will appear:
Click on Add and give executable path and new extension and click OK.

Close IIS and Run TestApp website by using the URL: http://localhost/Testapp/hello.text

The output will be as follows:

HttpForbiddenHandler

The sensitive files can be protected by Http Forbidden Handler. The Database driven web sites using MS
Access, the .mdb file has to be protected. To protect the .mdb files, we must follow the two steps given below:

1. Map .mdb file in IIS 2. Register the file extension in web.config with HttpForbiddenHandler.

In the Web.Config file, Add this Http handler section:

<httpHandlers><add verb="*" path="*.mdb" type="System.Web.HttpForbiddenHandler"/>


</httpHandlers>
Conclusion:
The Http Handlers are often useful when the services provided by the high-level page
framework abstraction are not required for processing the HTTP request. Common uses of
handlers include filters and CGI-like applications, especially those that return binary
data.
Creating and Registering a Custom HTTP Module

This walkthrough illustrates the basic functionality of a custom HTTP module. An HTTP module is called on every
request in response to the BeginRequest and EndRequest events. As a result, the module runs before and after
a request is processed. If the ASP.NET application is running under IIS 6.0, you can use HTTP modules to
customize requests for resources that are serviced by ASP.NET. This includes ASP.NET Web pages (.aspx files),
Web services (.asmx files), ASP.NET handlers (.ashx files), and any file types that you have mapped to ASP.NET.
If the ASP.NET application is running under IIS 7.0, you can use HTTP modules to customize requests for any
resources that are served by IIS. This includes not just ASP.NET resources, but HTML files (.htm or .html files),
graphics files, and so on. For more information, see ASP.NET Application Life Cycle Overview for IIS 5.0 and
6.0 and ASP.NET Application Life Cycle Overview for IIS 7.0.The example module in this topic adds a message to
the requested ASP.NET Web page at the beginning of any HTTP request. It adds another message after the page
has been processed. The module includes code that makes sure that it does not add text to a request for any
other file type.Each event handler is written as a private method of the module. When the registered events are
raised, ASP.NET calls the appropriate handler in the module, which writes information to the ASP.NET Web page.

Tasks illustrated in this walkthrough include the following:

• How to create the code for an HTTP module.


• How to register the module in the Web.config file.

Prequisites

In order to complete this walkthrough, you will need:

• Visual Studio or Visual Web Developer.

The walkthrough also assumes that you are working with IIS 6.0 or IIS 7.0. However, you can see the
functionality of the module even if you run the ASP.NET Development Server.

Creating a Custom HTTP Module Class

To begin, you will create a class file that implements the module.

To create a custom HTTP module class

1. Create an ASP.NET Web site and name it Handler.


You can choose any name for the Web site.
2. If the Web site does not already have an App_Code folder, create one under the root of the site.
3. In the App_Code directory, create a class file named HelloWorldModule.vb (for Visual Basic) or
HelloWorldModule.cs (for C#).
Alternatively, if you are using Visual Studio (not Visual Web Developer Express), you can create
HelloWorldModule as a class library project, compile it, and put the resulting assembly in the Web application's
Bin directory.
4. Add the following code to the class file:

using System;
using System.Web;
public class HelloWorldModule : IHttpModule
{
public HelloWorldModule()
{
}
public String ModuleName
{
get { return "HelloWorldModule"; } }

// In the Init function, register for HttpApplication


// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest +=
(new EventHandler(this.Application_BeginRequest));
application.EndRequest +=
(new EventHandler(this.Application_EndRequest));
}

private void Application_BeginRequest(Object source,


EventArgs e)
{
// Create HttpApplication and HttpContext objects to access
// request and response properties.
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<h1><font color=red>" +
"HelloWorldModule: Beginning of Request" +
"</font></h1><hr>");
}
}

private void Application_EndRequest(Object source, EventArgs e)


{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<hr><h1><font color=red>" +
"HelloWorldModule: End of Request</font></h1>");
}
}

public void Dispose() { }


}

5. Save and close the class file.


6. In the Build menu, click Build Web Site.

If the Web site does not build, correct any problems. The custom HTTP module must compile or you will
not be able to register the module.

Registering the HTTP Module in IIS 6.0 and IIS 7.0 Classic Mode

After you have created the HelloWorldModule class, you register the module by creating an entry in the
Web.config file. Registering the HTTP module enables it to subscribe to request-pipeline notifications.In IIS 7.0,
an application can run in either Classic or Integrated mode. In Classic mode, requests are processed basically
the same as they are in IIS 6.0. In Integrated mode, IIS 7.0 manages requests by using a pipeline that enables it
to share requests, modules, and other features with ASP.NET.The procedure for registering a module is different
in IIS 7.0 Classic mode and IIS 7.0 Integrated mode. This section describes the procedure for IIS 6.0 and IIS 7.0
Classic mode. The procedure for registering a module that is running in IIS 7.0 Integrated mode is described in
the next section.

To register the module for IIS 6.0 and IIS 7.0 running in Classic mode

1. If the Web site does not already have a Web.config file, create one under the root of the site.
2. Add the following highlighted code to the Web.config file:
<configuration>
<system.web>
<httpModules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</httpModules>
</system.web>
</configuration>

The code registers the module with the class name and the module name of HelloWorldModule.

Registering the HTTP Module in IIS 7.0 Integrated Mode

The process for registering a module in IIS 7.0 Integrated mode is slightly different than the process for IIS 7.0
Classic mode.

To register the module for IIS 7.0 running in Integrated mode

1. If the Web site does not already have a Web.config file, create one under the root of the site.
2. Add the following highlighted code to the Web.config file:

<configuration>
<system.webServer>
<modules>
<add name="HelloWorldModule" type="HelloWorldModule"/>
</modules>
</system.webServer>
</configuration>

You can also register the module by using IIS Manager. For more information, see Configuring Modules in IIS 7.0.

The code registers the module with the class name and the module name of HelloWorldModule.

Testing the Custom HTTP Module

After you have created and registered your custom HTTP module, you can test it.

To test the custom HTTP module

1. Add a new ASP.NET page in the application.


2. Right click the page you just added and select View in Browser.

The HTTP module appends a string to the start and end of the response. The module automatically runs
during any request for a file whose extension is assigned to ASP.NET. For more information, see HTTP
Handlers and HTTP Modules Overview.

You might also like