Implement URL rewriting and login verification through custom Module

Source: Internet
Author: User

First, we create a new class library named module, and then create a class named urlrewritemodule and implement the ihttphandler interface.CodeAs follows:

 
Public ClassUrlrewritemodule: ihttpmodule {Public VoidDispose (){Throw NewNotimplementedexception ();}Public VoidInit (httpapplication context ){Throw NewNotimplementedexception ();}}

Don't worry about the dispose method. Let's look at the init method Rename to see if it means initialization! Then let's look at its parameter httpapplication and think about whether we can do something if we have this thing. Hey hey, let's just output a helloworld first !!! Improved to the definition of httpapplication. Is there a inrequest event?Public Event EventhandlerBeginrequest;

In terms of words, is this event applied?ProgramLet's start the first execution of the event. That's right. Now, we can enter a line of text Hello World to the page as soon as the application is executed.

 

Public ClassUrlrewritemodule: ihttpmodule {Public VoidDispose (){Throw NewNotimplementedexception ();}
 Public  Void Init ( Httpapplication Context) {context. beginrequest + = New  Eventhandler (Context_beginrequest );} Void Context_beginrequest ( Object Sender, Eventargs E ){ Httpapplication APP = sender As  Httpapplication ; App. response. Write ("Hello World" );}
 
}

What is next? I only defined this class. How can I let the application know its existence? Open the Web. config file and add the following code. Note that in the system. Web node

 
<Httpmodules> <Add name ="Urlrewritemodule"Type ="Moduel. urlrewritemodule"/> </Httpmodules>

The first parameter name is the class name just defined. The second parameter type is the Assembly name and class name.

If you know the steps, you can implement the URL re-function!

Requirement: Set the original homedetail. aspx? Id = 1 is it pseudo-static! Let's look at the key lines of code.

 Void Context_beginrequest ( Object  Sender, eventargs e) {httpapplication app = Sender As  Httpapplication;  //  App. Context. response. Write ("hahahahaa ~~~ ");              String Requestpath = App. Context. Request. filepath;  String Filename =System. Io. Path. getfilename (requestpath); RegEx Reg = New RegEx ( "  Homedetail-(\ d00000000.html  "  ); Match m = Reg. Match (filename );  If  (M. Success ){  String Id = M. Groups [ 1  ]. Value; app. Context. rewritepath (  " Homedetail. aspx? Id =  " + ID );}  //  App. Context. response. Write (filename ); }

First obtain the virtual path of the current request, then obtain the specific file name, extract the ID from the regular expression, and finally rewrite the path.
The homelist. ASPX page is processed as follows:

 <! --  Original conversion address  -->                      <  A  Href  = "Homedetail. aspx? Id = <% # eval (" ID ") %  > "> <%  #  Eval  (  "  Name  "  )  %>  </  A >                      <! --  Address after Rewriting  -->                      <  A  Href  = "Homedetail-<% # eval ("  ID ") %  > . Html "> <%  #  Eval  ( "  Name  "  )  %>  </  A  > 

Run the following command:

OK. Note: With regard to URL rewriting, Microsoft has developed a component urlrewrite for us. With this component, you only need to simply configure the configuration file, if you are interested, search.

I don't think it's enough, right? Well, next I will try the entire login verification stuff.
In the past, whether to perform login verification is to determine the session value in page_load on each page to be verified. If it is null, the system will switch to the login interface, well, today we will write a module to implement this function to make the entire application effective. We found that only two of the 17 events in the httpapplication class can be operated on to the session through data search.

1. acquirerequeststate 2. postrequesthandlerexecute

First, create a sessionmodule class in the module class library to write these lines of code.

 

 1   Class  Sessionmodule: ihttpmodule  2   {  3   4           Public   Void Init (httpapplication context)  5   {  6 Context. acquirerequeststate + = New  Eventhandler (context_acquirerequeststate );  7   }  8   9           Void Context_acquirerequeststate ( Object  Sender, eventargs E)  10  {  11 Httpapplication APP = sender As  Httpapplication;  12               String Requestpath = App. Request. path;  13               String Filename = System. Io. Path. getfilename (requestpath );  14               If (App. Context. session [ "  Userinfo " ] = Null &&! Filename. Equals ( "  Login. aspx  "  ))  15   {  16 App. response. Redirect ( "  Login. aspx  "  );  17   } 18   }  19   20   21       22   23           Public   Void  Dispose ()  24   {  25               Throw   New  Notimplementedexception ();  26  }  27 }

14 lines to determine whether the session is empty and whether the requested page is not the login interface. If both are true, it is so easy to go To the login. ASPX page.

Add the code to the Web. config file.

<Httpmodules><AddName= "Urlrewritemodule"Type= "Moduel. urlrewritemodule"/><AddName= "Sessionmodule"Type= "Moduel. sessionmodule"/></Httpmodules>

Run OK and go directly to the homelist. ASPX page.

 

OK!

Attach the event execution sequence in httpappliction.

1. beginrequest (when ASP. NET responds to a request, it is the first event in the HTTP execution pipeline chain) Used in this article
2. authenticaterequest (this occurs when the security module has a user ID. Note: The authenticaterequest event signals that the configured authentication mechanism has authenticated the current request. Booking an authenticaterequest event ensures that the request is authenticated before processing the Attached Module or event handler .)
3. postauthenticaterequest (Note: This event is added in. NET Framework 2.0. This occurs when a user ID has been created for the security module. The postauthenticaterequest event is triggered after the authenticaterequest event occurs. The postauthenticaterequest event reservation function can access any data processed by postauthenticaterequest .)
4. authorizerequest (this occurs when the security module has authenticated user authorization. The authorizerequest event signals that ASP. NET has authorized the current request. Booking an authorizerequest event ensures that the request is authenticated and authorized before processing the Attached Module or event handler .)
5. postauthorizerequest (events added in. NET 2.0. This occurs when the user of the current request is authorized. The postauthorizerequest event signals that ASP. NET has authorized the current request. Booking a postauthorizerequest event ensures that the request is authenticated and authorized before processing the additional module or handler .)
6. resolverequestcache (when ASP.. Net completes authorization events so that the cache module can provide services for requests from the cache, thus skipping the execution of Event Handlers (such as a page or XML Web Services .)
7. postresolverequestcache (this occurs when ASP. NET skips the execution of the current event handler and allows the cache module to satisfy requests from the cache .) Create an event handler (corresponding to the page of the request URL) after the postresolverequestcache event and before the postmaprequesthandler event ).
8. postmaprequesthandler (this occurs when ASP. NET maps the current request to the corresponding event handler .)
9. acquirerequeststate
10. postacquirerequeststate
11. prerequesthandlerexecute (execute the event handler .)
12. postrequesthandlerexecuteNote: The session can be used.
13. releaserequeststate
14. postreleaserequeststate (after the postreleaserequeststate event, the response filter (if any) filters the output .)
15. updaterequestcache
16. postupdaterequestcache
17. endrequest

 

 

 

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: info-contact@alibabacloud.com 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.