I have previously written Asp.net URL rewriting series methods. Today I see another method. Go here.
ArticleSource: http://www.cnblogs.com/JinvidLiang/archive/2011/02/23/1962532.html
Previous series:
Asp.net URL rewriting method-sending Method
Asp.net URL rewriting method-use routing to implement Asp.net URL rewriting method-use httpmodules)
Use httpmodules to override URLs
First, write a class for processing URLs rewriting, and this class must inherit System. Web. ihttpmodule Interface. Program For example: Public Class Urlrewritemodule: system. Web. ihttpmodule
{
Public Void Init (httpapplication context)
{
Context. beginrequest + = New Eventhandler (context_beginrequest );
}
Public VoidDispose ()
{
//Throw new notimplementedexception ();
}
}
The urlrewritemodule class is the class for processing URLs rewriting. It inherits the ihttphandler interface and implements the two methods of this interface, init and dispose. Register your own method in the init method, as shown in the example above:
Content. beginrequest + = New Eventhandler (content_beginrequest );
Beginrequest is an event that is triggered when a new HTTP request is received. content_beginrequest is the method for processing the request. In addition, httpmodules can be registered in many ways, such as endrequest, error, disposed, and presendrequestcontent.
In the content_beginrequest method, specifically handle the details of URLs rewriting, for example, rewrite the http://www.cnblogs.com/rrooyy/archive/2004/10/24/56041.html to the http://www.cnblogs.com/archive.aspx? User = rrooyy & id = 56041 (Note: I did not carefully read the Dudu program. Here is just an example ). Then rewrite the generated URL with the httpcontext. rewritepath () method, as shown below:
Void Context_beginrequest ( Object Sender, eventargs E)
{
Httpcontext Context = (Httpapplication) sender). context;
// Get old URL
String URL = Context. Request. Path. tolower ();
// Generate a new URL
String Newurl = " ...... " ; // Detailed Process
// Rewrite URL
Context. rewritepath (newurl );
}
Reminder: newurl is not formatted.
Finally, register the URL rewriting class in Web. config. The format is as follows:
< Httpmodules >
< Add Type = "Classname, assemblyname" Name = "Modulename" />
< Remove Name = "Modulename" />
< Clear />
</ Httpmodules >
You can use the <add> label to register a class. <remove> you can remove a class. If a subdirectory does not want to inherit an HTTP module from the parent directory, you need to use this label; <clear/> All HTTP module registrations can be removed.