Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the difference between HttpHandler and HttpModule?

2025-01-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about the difference between HttpHandler and HttpModule. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Recently, I have received several questions: what is the difference between HttpHandler and HttpModule, which one should I choose?

The reason for this doubt is that both Request and Response objects can be accessed in these two types of objects and can handle requests.

To achieve the same goal, I used both HttpHandler and HttpModule. Now it seems that the examples I designed at the time were not to clarify the difference between HttpHandler and HttpModule, but to demonstrate how to design a service framework using HttpHandler and HttpModule.

Understand the ASP.NET pipeline

HttpHandler and HttpModule, both of which are related to the ASP.NET pipeline, so I think to understand these two types of objects must understand how the ASP.NET pipeline works.

The following figure reflects the processing flow of the ASP.NET pipeline:

This is a sequence chart, and we should understand it from two angles:

1. What are the invocation actions. two。 Who are the participants.

Each call action reflects the processing phase of the ASP.NET pipeline, which raises the corresponding events (except GetHandler,ProcessRequest), and HttpModule subscribes to these events to participate in the pipeline processing. Some of these phases also raise two events, and the complete pipeline event can be found in the MSDN documentation:

The following events will be executed by the HttpApplication class when the request is processed. Developers who want to extend the HttpApplication class need to pay particular attention to these events. 1. Validating the request examines the information sent by the browser and determines whether it contains potentially malicious tags. For more information, see ValidateRequest and script intrusion Overview. two。 If any URL has been configured in the UrlMappingsSection section of the Web.config file, URL mapping is performed. 3. Raises the BeginRequest event. 4. Raises the AuthenticateRequest event. 5. Raises the PostAuthenticateRequest event. 6. Raises the AuthorizeRequest event. 7. Raises the PostAuthorizeRequest event. 8. Raises the ResolveRequestCache event. 9. Raises the PostResolveRequestCache event. 10. Based on the file extension of the requested resource (mapped in the application's configuration file), the class that implements IHttpHandler is selected to process the request. If the request is for an object (page) derived from the Page class and the page needs to be compiled, ASP.NET compiles the page before creating an instance of the page. 11. Raises the PostMapRequestHandler event. twelve。 Raises the AcquireRequestState event. 13. Raises the PostAcquireRequestState event. 14. Raises the PreRequestHandlerExecute event. 15. Call the ProcessRequest method (or asynchronous version of IHttpAsyncHandler.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance processes the request. 16. Raises the PostRequestHandlerExecute event. 17. Raises the ReleaseRequestState event. 18. Raises the PostReleaseRequestState event. 19. If the Filter property is defined, response filtering is performed. 20. Raises the UpdateRequestCache event. 21. Raises the PostUpdateRequestCache event. twenty-two。 Raises the EndRequest event. 23. Raises the PreSendRequestHeaders event. 24. Raises the PreSendRequestContent event.

The picture also reflects the three main participants in ASP.NET:

1. HttpModule;2. HttpHandlerFactory;3. HttpHandler

Have you ever thought about how many participants there are in each of these three types of participants?

In order to answer this question clearly, I have prepared the following table:

Why introduce HttpHandlerFactory? Please take a look at my blog to explain the mapping process of HttpHandler, so I won't repeat it today.

Apart from HttpHandlerFactory, we can find that there should be only one HttpHandler in the ASP.NET pipeline, while HttpModule is optional.

Furthermore, can we understand that HttpHandler is the protagonist of the request (indispensable) and HttpModule is the supporting role (not necessary)?

Understand HttpApplication

We've been talking about the ASP.NET pipeline, so who's controlling the pipeline process?

The answer is: HttpApplication object.

1. HttpApplication subdivides its processing process and raises different events at different stages, so that HttpModule can be added to the request processing by subscribing to events.

two。 In the process of processing the request, the HttpApplication object mainly plays the role of controlling the processing flow.

3. HttpApplication will obtain an IHttpHandler instance at a fixed stage, and then hand over the response process of the request to the specific IHttpHandler to implement.

How does HttpApplication come into being and work?

1. HttpApplication objects are reused and created when HttpRuntime cannot get free instances from HttpApplicationFactory.

2. HttpRuntime will hand over each request to a HttpApplication object for processing.

3. The HttpApplication object is responsible for loading all HttpModule at initialization time.

4. Each HttpApplication object controls the pipeline process that belongs to it (as explained earlier).

HttpApplication is a very important type, many of its functions belong to the basic part of the framework, we do not need to call, so we usually do not use it.

I don't want the blog to digress. Let's take a look at today's protagonist.

Understand HttpHandler

When I mentioned earlier that HttpRuntime will hand over the request to HttpApplication, have you ever thought about the question: why doesn't HttpApplication process the request directly, but hand it over to a HttpHandler object?

The answer is: the content of each request may be different, and they are diverse, so ASP.NET uses the abstract factory pattern to process these requests. ASP.NET in the architecture of web.config allows us to specify that certain requests map to a HttpHandlerFactory, for example:

When a request matches a rule, ASP.NET calls the GetHandler method of the matching HttpHandlerFactory to get an HttpHandler instance, and finally a HttpHandler instance processes the current request.

How does HttpApplication submit the request to the HttpHandler instance for processing?

To understand this process, let's look at the definition of the IHttpHandler interface:

/ / this API is used to synchronously call / / the asynchronous version of the API. For more information, please see http://www.cnblogs.com/fish-li/archive/2011/11/20/2256385.html public interface IHttpHandler {/ / to get a value indicating whether other requests can use IHttpHandler instances. Bool IsReusable {get;} / / enables the processing of HTTP Web requests by implementing a custom HttpHandler of the IHttpHandler interface. Void ProcessRequest (HttpContext context);}

When HttpApplication passes a request to a HttpHandler instance for processing, it is called through the interface (the ProcessRequest method).

Topics related to HttpHandler:

1. Asynchronous HttpHandler: details the various asynchronous operations of ASP.NET.

two。 How to reuse HttpHandler: describe the mapping process of HttpHandler in detail.

Typical applications of HttpHanlder

Using System; using System.Web; public class Login: IHttpHandler {public void ProcessRequest (HttpContext context) {context.Response.ContentType = "text/plain"; string username = context.Request.Form ["name"]; string password = context.Request.Form ["password"]; if (password = = "aaaa") {System.Web.Security.FormsAuthentication.SetAuthCookie (username, false) Context.Response.Write ("OK");} else {context.Response.Write ("user name or password is incorrect.") ;}}

Usually I create an ashx file (HttpHanlder) in response to a particular request.

Therefore, we should understand HttpHanlder this way: a HttpHanlder is used to respond to a particular type of request.

What kind of HttpHanlder do we often use?

1. Aspx page. 2. Asmx service files. 3. Ashx file (general processor). 4. Implements a custom type for the IHttpHandler interface.

What do we usually do with HttpHanlder?

Looking at the goals achieved in the table, we can come to the conclusion that the purpose of using HttpHanlder is to generate response results.

Understand HttpModule

The purpose of designing HttpHanlder is clear: to generate response results.

So why design HttpModule?

As mentioned earlier, a HttpHanlder is used to handle a specific class of requests, and each aspx, ashx can be considered a class of requests. Sometimes we find that all pages may need some of the same checking features (such as identity checking), and if we can only use HttpHanlder, then we have to let all pages call those same checking functions. Who wants to do these repetitive things? Maybe some people will answer that they can implement a base class and call the check function in the base class. However, this approach can only solve the problem of repeated calls, and it will make the code lose flexibility (extensibility). Imagine: what if you need to add a new check function, or replace the original check logic with a new check method? Can only modify the base class?

HttpModule is designed to provide a flexible way to solve this problem of functional reuse. It uses the event (observer) design pattern to extract some functions needed by HttpHanlder to form different observer types, which can be compiled into a class library and shared by multiple website projects. To make the ASP.NET pipeline more flexible, ASP.NET allows us to freely configure the HttpModule we need in web.config, such as:

The configuration simply tells ASP.NET that these HttpModule need to be up and running. Have you ever wondered how these HttpModule got into the pipeline to run? I just said earlier that HttpModule subscribes to these events, so where are the events subscribed? Let's take a look at the definition of IHttpModule interface:

/ / this interface is used for synchronous calls / / Asynchronous usage Please refer to: http://www.cnblogs.com/fish-li/archive/2011/11/20/2256385.html public interface IHttpModule {/ / initialization module and prepare it for processing requests. Void Init (HttpApplication app); void Dispose ();}

Notice the key Init method, which passes in a parameter of type HttpApplication, and with the HttpApplication object, HttpModule can subscribe to all events of HttpApplication. Look at the following sample code:

Public class TestModule: IHttpModule {public void Dispose () {} public void Init (HttpApplication app) {app.PostAcquireRequestState + = new EventHandler (app_PostAcquireRequestState); app.PreRequestHandlerExecute + = new EventHandler (app_PreRequestHandlerExecute);} void app_PreRequestHandlerExecute (object sender, EventArgs e) {throw new NotImplementedException ();} void app_PostAcquireRequestState (object sender, EventArgs e) {throw new NotImplementedException () }}

Typical applications of HttpModule

Public class SetOutputCacheModule: IHttpModule {public void Init (HttpApplication app) {app.PreRequestHandlerExecute + = new EventHandler (app_PreRequestHandlerExecute);} void app_PreRequestHandlerExecute (object sender, EventArgs e) {HttpApplication app = (HttpApplication) sender; Dictionary settings = ConfigManager.Settings; if (settings = = null) throw new ConfigurationErrorsException ("SetOutputCacheModule failed to load configuration file.") / / implementation method: / / find the configuration parameters. If a matching request is found, set OutputCache OutputCacheSetting setting = null; if (settings.TryGetValue (app.Request.FilePath, out setting)) {setting.SetResponseCache (app.Context);}}

This Module is used to set the output cache for some requests that are indicated to be cached in the configuration file, and the sample code has been introduced in the previous blog to optimize the performance of ASP.NET sites without modifying the code. In fact, the most fundamental way to set up the output cache is to call some public methods of Response.Cache to modify the output response header.

What do we do with HttpModule?

1. Modify some requests (for example, the previous example modified the response header).

two。 Check check requests (such as authentication checks).

What requests can HttpModule handle?

1. The default is all requests to enter the ASP.NET.

two。 If you only need to process part of the request, make your own judgment (see the previous example).

A summary of the three objects

Earlier, I introduced HttpApplication,HttpHanlder and HttpModule respectively, and here I reorganize the relationship between the three.

In the process of processing the request, the HttpApplication object mainly acts as the control pipeline processing flow, which is responsible for promoting the whole processing flow. In addition to raising different events at different stages (for HttpModule to use), the HttpApplication object will also find a suitable IHttpApplicationFactory instance according to the current request, and finally get an instance of IHttpHandler to process the request.

These three types are designed to:

1. HttpApplication controls the processing flow and raises different events at different stages.

two。 Because of the diversity of requests, each request is processed by a HttpHandler object.

3. For some general-purpose functions, especially those that are independent of the response content, HttpModule is the most appropriate design.

Case demonstration

Q: I have some html files that need to be checked for identity authentication (judging Session). How can I implement it?

When you've made up your mind, let's take a look at my solution:

/ the processor used to respond to the HTML file / public class HtmlHttpHandler: IHttpHandler, IRequiresSessionState, IReadOnlySessionState {public void ProcessRequest (HttpContext context) {/ / get the filename string filePath = context.Server.MapPath (context.Request.FilePath) to request; / / check the response header with Fiddler. If you see this header, it means that it is processed by this code. Context.Response.AddHeader ("SeesionExist", (context.Session! = null? "yes": "no"); / / here, you can visit context.Session / / set the response content header context.Response.ContentType = "text/html"; / / output the file content context.Response.TransmitFile (filePath);}

Why should I choose HttpHandler in this case?

1. I need to respond to a type of request (all HTML files).

two。 Request to support Session

So I finally chose HttpHandler.

Q: I need to compress the response results of all ASP.NET requests. How can I achieve this?

When you've made up your mind, let's take a look at my solution:

/ public class GzipModule for the request to support gzip compressed output: IHttpModule {public void Init (HttpApplication app) {app.BeginRequest + = new EventHandler (app_BeginRequest);} void app_BeginRequest (object sender, EventArgs e) {HttpApplication app = (HttpApplication) sender / / determine whether the browser supports GZIP compression string flag = app.Request.Headers ["Accept-Encoding"]; if (string.IsNullOrEmpty (flag) = = false & & flag.ToLower (). IndexOf ("gzip") > = 0) {/ / set GZIP compression app.Response.Filter = new GZipStream (app.Response.Filter, CompressionMode.Compress) App.Response.AppendHeader ("Content-Encoding", "gzip");}}

Why should I choose HttpModule in this case?

There's only one reason: I need to set up all requests.

So I finally chose HttpModule.

How to choose?

Before concluding this blog, I would like to ask you again: do you know when to choose HttpHandler or HttpModule?

If you haven't seen it yet, I'll finally tell you how to identify it:

1. If you want to respond to a type of request, select HttpHandler.

two。 If you want to modify or check all requests (in short, no response results are generated), select HttpModule.

Finally, I would like to leave you with a question: which of the following functions provided by ASP.NET are implemented?

1. Session

two。 Identity authentication

3. URL authorization check

4. View tracking information through trace.axd

5. OutputCache

6. Prohibit downloading config files

7. Prohibit viewing and downloading source code files

After reading the above, do you have any further understanding of the difference between HttpHandler and HttpModule? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report