MSDN article: httpmodules [ourselves]

xiaoxiao2021-03-06  68

??????? ASP.NET A useful feature is the scalability of the HTTP pipeline, the so-called HTTP pipe refers to the path passed from the client to the server side. I will show you HTTP Modules this month. We can use HTTP Modules to extend the ASP.NET application - that is, add prerequisites and post-processes to our applications, and then process each arrival request by new applications. For example, if you want to add a custom authentication for your app, the most useful technology is a request to arrive at the client, and then start our introduction with the HTTP pipe below in custom HTTP Module.

HTTP pipeline

????? To understand HTTP Module in the ASPNET, you need to know how HTTP pipeline work. When an HTTP request passes the 80-port (HTTP common port, HTTPS, and verification sockets, the 443 port is commonly used) to reach the server, the request will be a series of HTTP pipes before really by your application processing. ????? Microsoft® Internet Information Services (IIS) is the first ring in a series of links. Although ASPNET has its own object model, process isolation mechanism, based on the session state management mechanism of the .NET Framework class, IIS is still used to pass the request to the ASPNET runtime. IIS maps ASPNET to ASPNET_ISAPI.dll, which is an ISAPI extension provided by ASPNET. The function of aspnet_isapi.dll is to pass the request to the ASPNET worker process aspnet_wp.exe. After this part of the work is completed, the request is packaged into an instance of the HTTPContext class then passes through the pipeline through a plurality of ASPNET classes. The HTTPContext class includes many members, such as responses, requests, including security information that you may want to know. ??????? Next, the request is transmitted to an HTTPApplication instance. This step is very useful for methods, data, and events that get applications. Because this class is critical to setting httpmoduls, I will introduce HTTPApplication. ?????? HTTPApplication object After accepting the request, pass it to one or several httpmodule objects. There are many system-level HTTP modules to provide services from status management to output cache. The number of modules that intercept the request is set by the machine level Machine.config and the Web.config file that applies the same program. Provides pretreatment and post-processing comparison in the ASP to be completed in the ISAPI filter. This shows that the ASP HTTP module is more simple and simpler.

?????? The last link in this series is httphandler. If you have used ASPNET for a while, you should be more familiar with System.Web.ui.page class. The page class is an instance of HTTPHANDER, which implements the IHTTPHANDLER interface. The class that implements the IHTTPHANDLER interface can pass the ProcessRequest method of this interface (HOOK) HTTP pipes and service requests.

Figure 1 HTTP Request

When each request arrives, if the request's URI points to an ASP.NET extension file, ASP.NET will find a class that implements the IHTTPHANDLER interface related to this extension in the web.config file. If you don't do any changes in your web.config file, ASP.NET will create a handler according to System.Web.ui.page when browsing an ASPX file. You can map a separate HTTP handler to its respective URI by setting up a web.config file. Figure 1 shows a process of an HTTP request through an HTTP pipe. Classes associated with httpmodule include: BeginRequest, AuthenticateRequest, AuthorizeRequest, etc. ASP.NET HTTP MODULES A http module is actually a class that implements the System.Web.ihttpmodule interface. Public interface httpmodule {? void dispose () ;? void init;} When an HTTPModule is coupled to the pipe (by the entry in the web.config file), the ASP.NET runtime call this module INIT and DISPOSE methods. When the module is attached to the HTTPApplication object, call the Init method when the module cancels the contact with the HTTPApplication. The init and dispose methods indicate a series of events exposed by the module to HTTPAppLication. These events include the start of the request, the request is completed, requested certification, and more. Note the parameters of the httpapplication type passing to the init method. In general, the init method takes over the HTTPApplication object and maps the event handler to the appropriate event.

FIG custom HttpModule 2 // This module, named HttpModules.CS will be compiled // into an assembly named HttpModules.dllusing System; using System.Web; namespace HttpModuleExamples {?? public class CustomHttpModule:? IHttpModule {???? ? // httpmodule members ????? public void init (httpapplication httpapp) {???????? httpapp.beginRequest = ??? ?????????? New EventHandler (this.OnbeginRequest ); ??????????? httpapp.endrequest = ?????????? New EventHandler (this.onendRequest); ?????} ????? public void dispose () {????????? // usually, nothing has to happen here ... ?????} ?????????? public void OnbeginRequest (Object) o, EVENTARGS EA) {???????? httpapplication httpapp = (httpApplication) o; ?? ???????? HTTPContext CTX = httpContext.current; ???????? ctx.response .Write ("Beginning Request"); ?????} ????? public void Onendrequest (Object O, Eventargs EA) {???????? httpApplication httpapp = (httpApplication) O; ??? ??????? httpContext ctx = httpContext.current; ???????? ctx.response.write ("ending Request "); ?????} ??}} Figure 2 gives some C # code, which defines a httpmodule attached to the application of BeginRequest and endRequest events, which provides simple pre-request for each request. Processing (before requesting processing) and after processing (after processing). These codes are compiled into a assembly and deployed to the bin folder. To install this handler to a series of sections of the application process, we only need to declare some of the httpmodule part of the web.config file as follows. The following code shows a normal ASPX file using httpmodule in the processing session: ASP.NET now starts with the OnBeginRequest method starting with the request of Custom HttpModule and the overcastRequest method at the end of the request to track all requests. When you browse to this page, you will see a simple ASPX page in Figure 3. Figure 3? A simple ASPX page in httpmodule You are not only able to intercept BeginRequest and endRequest events. Figure 4 shows the httpApplication event you can track and can be placed in HttpModule. Capturing these events simply establishes an event handler for events you want to handle. Figure 5 shows the C # code of the AuthenticateRequest event in httpmodule. Figure 4

EventOccursAcquireRequestStateWhen ASP.NET acquires the current state (for example, session state) associated with the current requestAuthenticateRequestWhen a security module has established the identity of the userAuthorizeRequestWhen a security module has verified user authorizationBeginRequestWhen the first event in the HTTP pipeline chain of execution responds to a requestDisposedWhen ASP.NET completes the chain of execution when responding to a requestEndRequestWhen the last event in the HTTP pipeline chain of execution responds to a requestErrorWhen an unhandled exception is thrownPostRequestHandlerExecuteWhen the ASP.NET handler (page, XML Web Service) finishes executionPreRequestHandlerExecuteJust before ASP. NET begins executing a handler such as a page or XML Web ServicePreSendRequestContentJust before ASP.NET sends content to the clientPreSendRequestHeadersJust before ASP.NET sends HTTP headers to the clientReleaseRequestStateAfter ASP.NET finishes executing all request hand lers; also causes state modules to save the current state dataResolveRequestCacheWhen ASP.NET completes an authorization event to let the caching modules serve requests from the cache, bypassing execution of the handler (the page or XML Web Service, for example) UpdateRequestCacheWhen ASP.NET Finishes Executing a Handler in Order To Let Caching Modules Store Responses That Will BE Used to Serve Subsequent Requests from the cache?

Figure 5 Intercepting AuthenticateRequest event

Using system;

Using system.Web;

Namespace httpmoduleexamples {

Public class customAuthentication: httpmodule {

// httpmodule members

Public void init (httpapplication httpapp) {

httpapp.beginRequest =

New EventHandler (this.onauthenticateRequest);

}

Public void dispose () {// usually, nothing has to happen here ...

}

// Event Handlers

Public void onauthenticateRequest (Object O, Eventargs EA) {

// do any customs management here-perhaps

// Custom Credentials.

}

}

}

Early end request

Intercepting HTTP Request Most Reasons is to end the request in advance when an error occurs. For example: If you handle authentication, when the result is an error, you need to stop this request when you pass authentication. If you have written a SOAP server, you may need a terminal request when a non-SOAP request arrives. There is a method called CompleteRequest in the HTTPApplication class that is used to complete the request. You can call CompleteRequest and set the StatusCode and StatusDescription properties of the Context object to notify the client. Figure 6 shows an intercepted request and ends it when the request is unsafe.

Figure 6? End an HTTP request in advance

Public Class TestSecureConnection: IHTTPModule

{

// httpmoule members

Public string modulename {...}

Public void init (httpapplication httpapp)

{

httpapp.beginRequest =

New EventHandler (this.onbeginRequest);

}

Public void dispose () {...}

Public Void OnbeginRequest (Object O, Eventargs EA)

{

HTTPApplication httpApp = (httpapplication) O;

HttpContext CTX = (httpContext) Ea.extendedInfo;

IF (! CTX.Request.IsecureConnection)

{

httpapp.completerequest ();

CTX.Response.statuscode = 403;

CTX.Response.StatusDescription =

"Uses SSL, PLEASE."

}

}

}

Figure 7 HTTPModules provided by the system

ClassDescriptionDefaultAuthenticationModuleInsures the presence of an Authentication object in the contextFileAuthorizationModuleVerifies that the remote user has permissions in Windows NT to access the file requestedFormsAuthenticationModuleTurns on ASP.NET forms authenticationPassportAuthenticationModuleProvides a wrapper around Passport authentication servicesSessionStateModuleProvides session state services for an applicationUrlAuthorizationModuleProvides URL-based authorization services for allowing or Denying Access to Specified ResourcesWindowsAuthenticationModuleTurns ON Windows / Iis Authentication for The Application System

Many ASP.NETs are increasing by using HttpModule technology, such as: including output cache, session status, Windows verification, form validation, Passport authentication, URL authentication, and file authentication. Figure 7 shows these properties and modules that implement these properties.

Each predefined httpmodule is in the machine.config file. Figure 8 shows these settings.

Figure? 8 predefined httpmodules registration

Attached to a series of httpmodule on an application represents a collection of IHTTPModule references, called httpmodulecollection, which can be accessed as the modules property of the HttPApplication class. At runtime, the collection includes all modules provided in all Machine.Config and modules defined in web.config. HttpModuleCollection is a series of reference to IHTTPModule, these modules or their names as keywords or Ordinal as keywords, as shown in Figure 9. Figure 10 shows the modules listed in the web page.

When the application starts, all HTTPModule is generally controlled by ASP.NET. If you want to manage these modules personally, you can use HTTPModulecollection to get a reference to any module and call the init or Dispose method. Or you can manually load an HTTPModule assembly and add a module based on a specific custom rule for your application.

Fig. 9 is judged which module is used?

public void ShowModules (Object o, EventArgs E) {? HttpApplication httpApp = ?? HttpContext.Current.ApplicationInstance ;? HttpModuleCollection httpModuleColl = ?? httpApp.Modules ;? Response.Write ( "") ;? String [] rgstrModuleNames ;? rgstrModuleNames = httpmodulecoll.allkeys ;? foreach (string strmodulename in rgstrmodulen) {??? response.write (strModulen); ??? response.write (");?}? response.write (");} <% @ Page language = "c #" ??? src = "usehttpmodules.cs" ??? inherits = "usehtpmodules" ??? trace = 'true'%>?

Figure 10 Attached HTTPModules

?

HttpModules and global.asax

ASP.NET applications may contain a file called global.asax (also called ASP.NET application file). Global.asax is located below your ASP.NET application. When the application is loaded at runtime, ASP.NET extracts the Global.asax file and generates a runtime object derived from HttPApplication. Global.asax is optional, but when it exists, it contains corresponding code from the ASP.NET and HTTP modules to the application level.

?

转载请注明原文地址:https://www.9cbs.com/read-120035.html

New Post(0)