Asp. NET HTTP modules and handlers

Source: Internet
Author: User
Tags filter anonymous extend http request httpcontext new features parent directory visual studio| Program Introduction

At the beginning of the internet age, the needs of clients are very limited;. htm files can meet their needs. However, over time, the expansion of client requirements extends beyond the functionality contained in. htm files or static files.
Developers need to expand or extend the functionality of the Web server. Web server vendors have designed different solutions, but all follow the same theme, "Inserting certain components into a Web server." All Web server supplemental technologies allow developers to build and insert components to enhance the functionality of the Web server. Microsoft has proposed the ISAPI (Internet Server API), Netscape has proposed NSAPI (Netscape Server API) and so on.

ISAPI is an important technology that allows us to enhance the ability of an ISAPI-compliant Web server (IIS is a Web server that is compatible with ISAPI). We use the following components to achieve this goal:

· ISAPI Extension

· ISAPI filters

ISAPI extensions are implemented using the WIN32 dynamic link library. You can think of an ISAPI extension as an ordinary application. The process target of the ISAPI extension is the HTTP request. This means you have to call them to activate them. You can think of an ISAPI filter as just a filter. Each time the client makes a request to the server, the request passes through the filter. The client does not need to specify a filter in the request, simply send the request to the Web server, and the Web server passes the request to the relevant filter. The filter may then modify the request, perform some login operations, and so on.

Because of the complexity of these components, it is difficult to implement them. Developers have had to use C/COM + + to develop these components, but for many people, using C + + to develop is simply synonymous with pain.

So what does provide to achieve these functions? Asp. NET provides HttpHandler (HTTP handlers) and HttpModule (HTTP modules).

Before delving into the details of these components, it is valuable to understand how HTTP requests are processed through HTTP modules and HTTP handlers.

Building the sample application

I set up some of the following C # projects to demonstrate different components of the application:

· Newhandler (HTTP handler)

· Webapp (Demo HTTP handler)

· Securitymodules (HTTP Module)

· WEBAPP2 (Demo HTTP module)

Installation steps for these applications:

· Unlock the code in the attached zip file.

· Create two virtual directories WebApp and WEBAPP2; point the two directories to the actual physical directory of the WebApp and WEBAPP2 applications.

· Copy the Newhandler.dll file from the Newhandler project to the WebApp application's Bin directory.

· Copy the SecurityModules.dll files from the Securitymodules project to the bin directory of the WEBAPP2 application.

Asp. NET request process

Asp. NET request processing is based on the piping model, in which the HTTP request is passed to all modules in the pipeline. Each module receives HTTP requests and has Full control permissions. The module can handle the request in any way that it thinks fit. Once the request passes through all HTTP modules, it is eventually processed by the HTTP handler. The HTTP handler processes the request, and the result passes through the HTTP module in the pipeline again:

Note that during the processing of HTTP requests, only one HTTP handler can be invoked, but multiple HTTP modules may be invoked.

HTTP handlers

An HTTP handler is a. NET component that implements the System.Web.IHttpHandler interface. Any class that implements the IHttpHandler interface can be used to process incoming HTTP requests. HTTP handlers are somewhat similar to ISAPI extensions. The difference between HTTP handlers and ISAPI extensions is that they can be called directly in the URL using the file name of the HTTP handler, similar to the ISAPI extension.

The HTTP handler implements the following methods:

Method Name Description ProcessRequest This method is actually the core of the HTTP handler. We call this method to handle HTTP requests. IsReusable we call this property to determine whether an instance of an HTTP handler can be used to handle the same other type of request. HTTP handlers can return TRUE or false to indicate whether they can be reused.
You can use Web.config or Machine.config files to map these classes to HTTP requests. When the mapping is complete, instantiates the HTTP handler when the corresponding request is received. We will explain how to define all of these details in the Web.config and/or machine.config files.

Asp. NET also supports extensions of HTTP handlers through the IHttpHandlerFactory interface. Asp. NET provides the ability to route HTTP requests to objects that implement the IHttpHandlerFactory interface's classes. In addition, ASP. NET also utilizes the factory design pattern. This pattern provides an interface for building a set of related objects without providing a specific class of functionality. Simply put, you can think of a class that is used to establish an HTTP handler object that relies on passing in parameters as a factory (factory). We do not specify the specific HTTP handlers that need to be instantiated; The HTTP handler factory handles this transaction. The advantage of this is that if the implementation of the object that implements the IHttpHandler interface changes in the future, the client will not be affected as long as the interface remains the same.

The following is a list of methods in the IHttpHandlerFactory interface:

Method Name Description GetHandler This method is responsible for establishing the appropriate handler and returning its pointer to the calling code ( runtime). The handler object returned by this method should implement the IHttpHandler interface. Releasehandler This method is responsible for releasing the HTTP handler after the request processing completes. The Factory implementation determines its operation. The Factory implementation can be an actual instance of destroying, or it can be put into a buffer pool for later use.
Registering HTTP handlers and HTTP handler factories in a configuration file

Asp. NET maintains its own configuration information in the following configuration file:

· Machine.config

· Web.config

The Machine.config file contains configuration settings information that applies to all Web applications that are installed on the computer.

Web.config files are specific to each Web application. Each Web application has its own Web.config file. Any subdirectory of the Web application may also contain its own Web.config files, which enables them to overwrite the settings information of the parent directory.
To add an HTTP handler to our Web application, you can use the
<add verb= "Supported HTTP Verbs" path= "path" type= "Namespace.ClassName, AssemblyName"/>
In the XML above,

· The verb property specifies the HTTP actions that are supported by the handler. If a handler supports all HTTP actions, use "*" or use a comma-delimited list to list the supported actions. So if your handler only supports HTTP GET and post, then the verb attribute should be "go, post."

· The Path property specifies the paths and file names (which can contain wildcard characters) that need to be invoked by the handler. For example, if you want your handler to be invoked only when the file is requested, the path attribute contains "TEST.XYZ", and if you want all files containing the. xyz suffix to call the handler, the path attribute should contain "*.xyz."

· The Type property specifies the actual type of the handler or handler factory using a combination of namespace, class name, and part name. Asp. NET runtime first searches the part DLL in the application's Bin directory, and then searches in the global parts buffer (GAC).

Asp. How the NET runtime uses HTTP handlers

Whether you believe it or not, ASP. NET uses HTTP requests to achieve a large number of its own capabilities. Asp. NET uses handlers to handle. aspx,. asmx,. Soap, and other files.

The following is a fragment from the Machine.config file:

<add verb= "*" path= "Trace.axd" type= "System.Web.Handlers.TraceHandler"/>
<add verb= "*" path= "*.aspx" type= "System.Web.UI.PageHandlerFactory"/>
<add verb= "*" path= "*.ashx" type= "System.Web.UI.SimpleHandlerFactory"/>
<add verb= "*" path= "*.config" type= "System.Web.HttpForbiddenHandler"/>
<add verb= "Get,head" path= "*" type= "System.Web.StaticFileHandler"/>
. . . . . .
. . . . . .
In the configuration information above you can see that all requests for the. aspx file are handled by the System.Web.UI.PageHandlerFactory class. Similarly, all requests for. config files and other files (which cannot be accessed directly by the client) are handled by the System.Web.HttpForbiddenHandler class. As you may have guessed, when accessing these files, the class simply returns an error message to the client.

Executing an HTTP Handler

Now you'll see how to implement an HTTP handler. So what do we do with our new handler? As I mentioned earlier, most of the handlers are used to add new functionality to the Web server; Therefore, I'll set up a handler to handle the new file type--Files with the. 15seconds extension. After we have established this handler and registered in our Web application's Web.config file, all requests for. 15seconds files will be processed by this new handler.

You may be considering how to use this handler. What if you want to introduce a new server scripting language or dynamic server file (such as ASP, ASPX)? You can write one of your own handlers for it. Similarly, what should you do if you want to run Java applets, JSPs, and other server-side Java components on IIS? One way is to install certain ISAPI extensions (such as Allaire or Macromedia Jrun). You can also write your own HTTP handlers. Although this is a complex transaction for third-party vendors, such as Allaire and Macromedia, it is an attractive option because their HTTP processing can access all the new features exposed by the runtime.

Implementing our HTTP handler consists of the following steps:

1. Write a class that implements the IHttpHandler interface.

2. Register this handler in the Web.config or Machine.config file.

3. Map file extensions (. 15seconds) to the ISAPI extension DLL (aspnet_isapi.dll) in Internet Services Manager.

First step

Create a new C # class library project in Visual Studio.NET and name it "MyHandler." Visual Studio.NET automatically adds a class called "Class1.cs" to your project. Rename it "Newhandler"; Open the class in the code window and change the name of the class and the name of the constructor to "Newhandler".

The following is the code for the Newhandler class:

Using System;
Using System.Web;

Namespace MyHandler
public class Newhandler:ihttphandler
Public Newhandler ()
TODO: Add construction logic here

#region implementation of IHttpHandler
public void ProcessRequest (System.Web.HttpContext context)
HttpResponse Objresponse = context. Response;
Objresponse.write ("Objresponse.write ("</body> }

public bool IsReusable
return true;
As you can see in the ProcessRequest method, the HTTP handler accesses all the internal objects passed to it as parameters through the System.Web.HttpContext object. The implementation of the ProcessRequest method simply extracts the HttpResponse object from the context object and sends some HTML to the client. Similarly, IsReusable returns True, indicating that the handler can be reused as a process for other HTTP requests.

We compile the code above and place it in the bin directory of the WebApp virtual directory.

Second Step

In the Web.config file, register the handler by adding the following text:

<add verb= "*" path= "*.15seconds" type= "Myhandler.newhandler,myhandler"/>
Third Step

Since we have established a handler for handling the new extension file, we also need to tell IIS about the extension and map it to If you try to access the Hello.15seconds file without performing this step, IIS simply returns the file instead of passing it to the runtime. The result is that the HTTP handler will not be invoked.

Run Internet Services Manager, right-click the default Web site, select Properties, move to the Home Directory Options page, and click the Configure button. The Application Configuration dialog box bounced out. Click the Add button and enter the Aspnet_isapi.dll file path in the executable field, in the extended field input. 15seconds. The other fields do not need to be processed, and the dialog box looks like this:

Click the Confirm button to close the application configuration and Default Web Site Properties dialog box.

Now that we run Internet Explorer and enter Url:http://localhost/webapp/hello.15seconds, we see the following page:

dialog state in HTTP handler

Maintaining the dialog state is the most common transaction performed by a Web application. HTTP handlers also need access to these dialog states. However, the default settings for the HTTP handler do not activate the dialog state. In order to read and/or write state data, an HTTP handler is required to implement one of the following interfaces:

· IRequiresSessionState

· Ireadonlysessionstate.

When an HTTP handler needs to read and write the dialog data, it must implement the IRequiresSessionState interface. If it only reads the conversation data, implement the Ireadonlysessionstate interface.

Both of these interfaces are tag interfaces and do not contain any methods. So, if you want to activate the dialog state of the Newhandler handler, declare the Newhandler class like the following code:

public class Newhandler:ihttphandler, IRequiresSessionState
HTTP Module

The HTTP module is a. NET component that implements the System.Web.IhttpModule interface. These components insert themselves into the request processing pipeline by registering themselves in certain events. When these events occur, ASP. NET invokes an HTTP module that is interested in the request, so that the module can process the request.

The HTTP module implements the following methods of the IHttpModule interface:

Method Name Description Init This method allows the HTTP module to register its own event handlers with events in the HttpApplication object. Dispose this method gives the HTTP module the opportunity to perform cleanup before the object is garbage collected.
HTTP modules can be registered with the following methods exposed to the System.Web.HttpApplication object:

The event name Description AcquireRequestState This event when the runtime is ready to receive the dialog state of the current HTTP request. AuthenticateRequest this event when the runtime is ready to authenticate the user. AuthorizeRequest this event when the runtime is ready to authorize users to access resources. BeginRequest this event when a new HTTP request is received by the runtime. Disposed this event when completes the processing of an HTTP request. This event is raised before EndRequest sends the response content to the client. Error raises this event when an unhandled exception occurs during processing of an HTTP request. PostRequestHandlerExecute This event when the HTTP handler finishes executing. PreRequestHandlerExecute raises this event before starts the handler for the HTTP request. After this event, forwards the request to the appropriate HTTP handler. Presendrequestcontent raises this event before sends the response content to the client. This event allows us to change the response content before the content arrives at the client. We can use this event to add content to the page output for all pages. such as General menu, header information, or foot information. Presendrequestheaders raises this event before sends the HTTP response header information to the client. This event allows us to change its contents before the header information arrives at the client. We can use this event to add cookies and custom data to the header information. ReleaseRequestState this event when ends the search request handler execution. Resolverequestcache we raise this event to determine if we can end the request using the content returned from the output buffer. This depends on how the Web application's output buffers are set. Updaterequestcache This event occurs when the completes the processing of the current HTTP request and the output is ready to be added to the output buffer. This depends on how the output buffering for the Web application is set.
In addition to these events, we can use four of events. We can use these events by implementing some of the methods in the Global.asax file of the Web application.

These events are:

· Application_OnStart

This event is raised when the first request arrives at the Web application.

· Application_OnEnd

This event is raised before the application is ready to terminate.

· Session_OnStart

The first request from the user dialog raises this event.

· Session_OnEnd

This event is triggered when the conversation is abandoned or the conversation is overdue.

Registering the HTTP module in a configuration file

After we have established the HTTP module and copied it to the Web application's Bin directory or the global Assembly cache, we should then register it in Web.config or machine.config.

We can use the
Because configuration settings information is inheritable, the subdirectory inherits configuration settings information from the parent directory. As a result, subdirectories may inherit unwanted HTTP modules (which are part of the parent configuration information); Therefore, we need a way to remove these unwanted modules. We can use the <remove> node, and if we want to remove all HTTP modules inherited from the application, you can use the <clear> node.

The following code is a generic example of adding an HTTP module:

<add type= "classname, AssemblyName" Name= "ModuleName"/>
The following code is a common example of removing an HTTP module from an application:

<remove name= "ModuleName"/>
In the XML above:

· The Type property specifies the actual type of the HTTP module in the form of a class and part name.

· The Name property specifies the friendly name of the module. Other applications can use this name to identify the HTTP module.

Asp. NET runtime how to use the HTTP module

Asp. NET runtime uses HTTP modules to implement certain special functions. The following fragment comes from the Machine.config file, which shows the HTTP modules installed at runtime

<add name= "OutputCache" type= "System.Web.Caching.OutputCacheModule"
<add name= "Session" Type= "System.Web.SessionState.SessionStateModule"/>
<add name= "WindowsAuthentication"
Type= "System.Web.Security.WindowsAuthenticationModule"/>
<add name= "FormsAuthentication"
Type= "System.Web.Security.FormsAuthenticationModule"/>
<add name= "Passportauthentication"
Type= "System.Web.Security.PassportAuthenticationModule"/>
<add name= "URLAuthorization"
Type= "System.Web.Security.UrlAuthorizationModule"/>
<add name= "Fileauthorization"
Type= "System.Web.Security.FileAuthorizationModule"/>
Asp. NET uses some of the HTTP modules above to provide services such as authentication and authorization, dialog management, and output buffering. Because these modules are registered in the Machine.config file.

Implement an HTTP module that provides security services

Now we implement an HTTP module that provides security services for our web applications. The HTTP module basically provides a custom identity authentication service. It will receive the credentials in the HTTP request and determine if the voucher is valid. If it works, what are the user-related roles? Through the User.Identity object, it associates these roles with the identity of the user who accesses our Web application page.
The following is the code for the HTTP module:

Using System;
Using System.Web;
Using System.Security.Principal;

Namespace Securitymodules
General description of the CLASS1.

public class Customauthenticationmodule:ihttpmodule
Public Customauthenticationmodule ()
public void Init (HttpApplication r_objapplication)
Registers an event handler with the Application object.
R_objapplication.authenticaterequest =
New EventHandler (this. AuthenticateRequest);

public void Dispose ()
Empty here because we don't need to do anything.

private void AuthenticateRequest (Object R_objsender,eventargs R_objeventargs)
Identify the user's credentials and identify the user role.
1. HttpApplication objapp = (HttpApplication) R_objsender;
2. HttpContext objcontext = (HttpContext) Objapp.context;
3. if ((objapp.request["userid"] = = null) | |
4. (objapp.request["password"] = = null))
5. {
6. ObjContext.Response.Write ("7. ObjContext.Response.End ();

9. String UserID = "";
UserID = objapp.request["userid"]. ToString ();
A. String password = "";
Password = objapp.request["Password"]. ToString ();
String[] Strroles;
Strroles = authenticateandgetroles (userid, password);
if ((strroles = null) | | (strroles.getlength (0) = = 0))
16. {
ObjContext.Response.Write ("Find this user ID and password Objapp.completerequest ();

GenericIdentity objidentity = new GenericIdentity (userid,
Objcontext.user = new GenericPrincipal (objidentity, strroles);

Private string[] Authenticateandgetroles (string r_struserid,string r_strpassword)
string[] strroles = null;
if ((R_struserid.equals ("Steve")) && (R_strpassword.equals ("15seconds"))
Strroles = new String[1];
Strroles[0] = "Administrator";
else if ((R_struserid.equals ("Mansoor")) && (R_strpassword.equals ("Mas"))
Strroles = new String[1];
Strroles[0] = "User";
return strroles;
Let's look at the code above.

We started with the Init function. This function inserts the handler's AuthenticateRequest event into the list of event handlers for the application (application) object. This will cause the Authenticationrequest event to be raised when application calls the method.

After our HTTP module is initialized, we can call its AuthenticateRequest method to authenticate the client request. The AuthenticateRequest method is the core of the security/identity authentication mechanism. In this function:

Lines 1 and 2 extract the HttpApplication and HttpContext objects. 3 to 7 lines detect if the user ID or password is not provided. If not provided, an error message is displayed and the request processing terminates.

9 to 12 lines extract the user ID and password from the HttpRequest object.

The 14 line calls a helper function called Authenticateandgetroles. This function primarily performs authentication and determines the user role. The code above is hard-coded (hard-coded), allowing only two users, but we can extend this method and add code to interoperate with the user database and retrieve the user's role.

Rows 16 through 19 detect whether a role is associated with the user. If not, it means that the voucher passed to us does not pass validation, so the voucher is invalid. Therefore, an error message is sent to the client and the request is terminated.

Lines 20 and 21 are important because these two lines actually tell the http runtime's identity to the logged-on user. After the two lines have been successfully executed, our ASPX page will be able to access the information using the user object.

Now let's take a look at how this authentication mechanism works. Currently we only allow the following two users to log on to the system:

· User id = Steve, Password = 15seconds, role = Administrator
· User ID = Mansoor, Password = mas, role = user

Note that the user ID and password are case sensitive (case-sensitive).

First try not to provide a credential login system, in IE input http://localhost/webapp2/index.aspx will see the following message:

You are now attempting to log on to the system using the user ID "Steve" and the password "15seconds". Enter http://localhost/webapp2/index.aspx?userid=Steve&password=15seconds you will see the following welcome message:

You are now attempting to login to the system using the user ID "Mansoor" and the Secret Code "MAS". Input Aspx?userid=mansoor&password=mas ">http://localhost/webapp2/index.aspx?userid=mansoor&password= Mas you will see the following welcome Message page:

You are now attempting to log on to the system using the wrong user ID and password combination. Enter HTTP://LOCALHOST/WEBAPP2/INDEX.ASPX?USERID=MANSOOR&AMP;PASSWORD=XYZ you will see the following error message:

This shows that our security module is working. You can extend the security module by using Database access code in the Authenticateandgetroles method.

To make all the parts work, we have to make some changes to the Web.config file. First, because we want to use our own authentication, we do not need other authentication mechanisms. To do this, change the <authentication> node in the webapp2 Web.config file as follows:

<authentication mode= "None"/>
Similarly, anonymous users are not allowed to visit our web site. Add the following statement to the Web.config file:

<deny users= "?" />
Used to enable at least anonymous access to files that are used to provide credentials. Use the following configuration settings information in the Web.config file to index.aspx as the only file that can be accessed anonymously:

<location path= "Index.aspx"
<allow users= "*"/>

You may already be aware of having HTTP handlers and modules after the ASP. NET has given developers a powerful energy source. Insert your own component into the request processing pipeline and enjoy its advantages.

As an exercise, you should further improve the program to make the sample authentication module more flexible and adaptable to the needs of the user.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.