HttpHandler HttpModule Beginners

ASP.Net processing Http Request, using the Pipeline (pipe) mode, the request is processed by the respective HttpModule, HttpHandler then reaches, after HttpHandler processed, still through respective HttpModule Pipeline processing, and finally sent to the client browser HTML in.

Lifecycle involves several important objects: HttpHandler, HttpModule, IHttpHandlerFactory, their execution order execution process is roughly like this:

client sends page request is intercepted by an IIS process, which according to the page suffix (.aspx) to apply different call different pages handlers (.asp-> asp.dll; .aspx-> ISAPI.dll ). The page handler in the process, will have to go through HttpModule, HttpHandler treatment: the former HttpModule for handling some of the events before and after the page processing and handling, which HttpHandler to process real page.
As mentioned earlier, HttpModule on the page will be treated before treatment and after page, so it will not affect the actual page request. Often used in adding some information (such as copyright notice), etc. to the head or tail of each page. Have seen some free space, we go up the page to upload, browse, we found that a lot more small ads in the head and tail of each page .... If you understand the principles HttpModule, and to do this it is not very difficult ~


IHttpHandler difference IHttpModule and finishing
1. IHttpModule priorities first, after IHttpHandler Note:.. Module which depends on your response to the event, some of the events are run before Handler, some are run after Handler
processing 2. requests on:
   IHttpModule belong outside their type, regardless of what the client requests a file, it will call to; for example, requests aspx, rar, html's.
   the IHttpHandler belong to the type of picky eaters, only ASP.net registered file types (for example, aspx, asmx etc.) will turn to call it.
3.IHttpHandler content of the response generated in accordance with your request, the request for the IHttpModule pretreatment, such as to verify, modify, filter, etc., can also be processed in response to

 

ASP.Net configuration of the system itself has a lot HttpHandler and HttpModule, such as .Net standard to handle aspx page file, and the page file in standard event processing. View

% System% / Microsoft.NET \ Framework \ v2.0.50727 \ web.config file in the CONFIG directory httpHandlers and httpModules node, you can see these configurations. If you are interested, you can use Reflector to view .Net classes and methods related to the system to learn how to deal with .Net as well as what has been done deal.

.Net also provides a mechanism to develop custom HttpHandler and HttpModule ', can be used to intercept HttpRequest complete custom processing. HttpModule inherited System.Web.IHttpModule interface, to achieve their own HttpModule class. Two methods must implement the interface: Init and Dispose. In the Init, you can add the need to intercept events; Dispose for the release of resources, if you created your own resource object in the Init, please release Dispose in.

namespace MyModule

{

    public class MyHttpModule : IHttpModule

    {

        public MyHttpModule()

        {

        }

        // Init method to register HttpApplication events.

        public void Init(HttpApplication r_objApplication)

        {

            r_objApplication.BeginRequest += new EventHandler(this.BeginRequest);

        }

        public void Dispose()

        {

        }

        private void BeginRequest(object r_objSender, EventArgs r_objEventArgs)

        {

            HttpApplication objApp = (HttpApplication)r_objSender;

            objApp.Response.Write ( "URL you requested is" + objApp.Request.Path);

        }

    }

Copy the compiled dll file to the bin directory of your web project, the configuration in the web.config file system.web node web project:

    <httpModules>

      <add name="test" type="MyModule.MyHttpModule,MyHttpModule"/>

    </ httpModules>
    so defined will self HttpModule class MyHttpModule inserted into the web HttpModule current in the Pipeline. HttpModule main function of individual events Application of the interception, completed his deal with these events. In fact, if they develop some projects, working directly in the Global.asax enough. If it is to develop a Framework or are components of some aspects you need to be added in the event processing, develop custom HttpModule, you can avoid using Framework or components have to manually add code in Global.asax. Currently thought to develop from the use of defined HttpModule, there is a global identity / authority validation, custom site access / operation log record in management / debugging purposes on site to monitor tracing. Of course, if it is bound to develop a custom HttpHandler the Framework, HttpModule 'may be used in some other special handling. Note case-sensitive, as is the case-sensitive web.config as an XML file. "Type = MyHttpModuleTest.MyHttpModule, MyHttpModule" tells us that the system will request to the http request is located MyHttpModuleTest.MyHttpModule class MyHttpModule.dll files to deal with. HttpHandler is full of interception Http Request.
    First, inheritance System.Web.IHttpHandler interface, to achieve their own HttpHandler class. ProcessRequest must implement the methods and properties IsReusable interface. ProcessRequest method completed processing for each Http Request, HTML, transmits the processing result to the output buffer. IsReusable .Net Framework property is invoked to determine whether this instance HttpHandler may be reused for the same type of other Request process.
    If you own HttpHandler class, you need to read or write Session values need to inherit an interface IRequiresSessionState. This interface has no methods, just a marker interface. After inheriting this interface, you can access Session in their own HttpHandler, you can write values in Session.

 

namespace MyHandler

{

    public class MyHttpHandler : IHttpHandler, IRequiresSessionState

    {

        public MyHttpHandler() { }

        public bool IsReusable

        {

            get { return true; }

        }

        public void ProcessRequest(HttpContext context)

        {

            HttpResponse objResponse = context.Response;

            objResponse.Write("This request is handled by MyHttpHandler");

        }

    }

}

    Copy the compiled dll file to the bin directory of the web project.
    Next, so to test MyHttpHandler. We configured a file type to .cc suffix name for the IIS, with our written MyHttpHandler to deal with.
    First, in the Configuration IIS configuration inside the site, add items one pair Application Extention Mapping .cc extension process.   
    Then, in the web.config node web project configuration:

    <httpHandlers>

      <add verb="*" path="*.cc" type="MyHandler.MyHttpHandler,MyHandler"/>

    </httpHandlers> 

    This verb attribute configuration HttpHandler those HTTP processing methods such as GET, POST, etc., if all of the processing method, use *. The path attribute configured HttpHandler which files are processed, for example, it may be myfile.cc, if it is to handle all .cc files, use * .cc.
    In this way, access to this type of all .cc files on the site, by MyHttpHandler process. Use http: // localhost / site virtual directory /a.cc access the test site, you can see the test results. Of course, a.cc this file on a Web server that does not exist.

    Use HttpHandler, the typical open source projects have Maverick .Net Web MVC's. Maverick use a Dispatcher class intercepts all Http Request, as he submitted .m extension to the Web server request, Dispatcher, the .m suffix removed, extracted Command Name, and then the command name from the configuration file loading the flow process, forming a chain, each command sequentially and view the chain is processed, the processing result of each command and may choose to view the different processing branches in the chain, in the Step processing result of each processing Response HTML written in the buffer output.
    Overall, Maverick framework architecture concept is very good, but there are obvious flaws, have the time to write about it in detail of the architecture and needs to be improved.

    In short, the HttpModule, HttpHandler, and the use of Ajax and other client will be packaged together, can bring a very large room for improvement in the development of web projects.

We often see a lot of sites with access to the article when it is ***. Html or ***. Shtml (such as log access the effect of this blog), the time to write this file does not exist on the server, then why would this effect occurs it is because the Web server to perform a rewrite of URL, the URL access rewritten internal access page based on specific format to achieve, it is easy for users to understand the benefits, but search engines can better the revenue your website, of course, there are many other benefits, there is not introduced one by one. 
This article is talking about using the HttpHandler Asp.Net achieve URL rewriting, it implements the principle see here, this program can handle any Url, because I use the URL misplaced in the program, only the file name is digital access It is then processed, and refers to the implementation of a new page in the inside, and outputs the data, as follows:

        public void ProcessRequest(HttpContext Context)

        {

            try

            {

                // declare Request        

                HttpRequest Request = Context.Request;

                // get the absolute path of antecedents Url       

                string Url = Request.Url.AbsolutePath;

                Start character number of intervals // Web document to take access

                int RegStart = Url.LastIndexOf("/") + 1;

                // declare a file name of the Web to determine whether all digital

                Regex Reg = new Regex(@"\d+");

                // use regular expressions to match

                if (Reg.IsMatch (Url, RegStart))

                {

                    // If the web file name is a number, it is determined that the query related articles, performing a specified page

                    Context.Server.Execute("~/PermaLink.aspx?id=" + Reg.Match(Url, RegStart).Value);

                }

            }

            catch

            {

                Context.Response.Redirect(Context.Request.Url.ToString());

            }

        }

Of course, you first need to do is to build a class, and inherits from IHttpHandler, then copy into the code, and compile. In a Web project To use this feature, you need to add the following sentence in your web.config inside:

     <httpHandlers>

      <add verb="*" path="*.shtml" type="HttpHandle.UrlRewrite" />

</httpHandlers>

At the same time, also conducted in IIS for the Web project configuration, the properties of the Web project, in the main directory option card, to execute permissions to "Scripts and executables" and then open the configuration, plus extensions in the application extended file format to be rewritten. Well, everything is in place, only a strong run.

Reproduced in: https: //www.cnblogs.com/zhangchenliang/archive/2012/12/29/2839152.html

Guess you like

Origin blog.csdn.net/weixin_34129145/article/details/93495315