Address: http://www.cnblogs.com/prolifes/articles/1235684.html
1. What is URL rewriting?
URL rewriting is the process of intercepting incoming Web requests and automatically redirecting requests to other URLs. For example, if the browser sends a request for Hostname/101. aspx, the server automatically directs the request to http: // hostname/list. aspx? Id = 101.
URL rewriting has the following advantages:
L shorten the URL and hide the actual path to improve security
L easy for users to remember and type.
L easy to be indexed by search engines
Ii. Basic Method for URL rewriting
1. Create a class project urlrewriter. Three classes including urlrewriter. config. CS, urlrewriter. Form. CS, and urlrewriter. Module. CS are added to the project.
Using system; <br/> using system. configuration; <br/> using system. collections; </P> <p> namespace urlrewriter. config <br/> {<br/> // define a custom section containing a simple element and a collection of the same element. <br/> // It uses two custom types: urlscollection and urlsconfigelement. <br/> public class urlsconfig <br/> {<br/> Public static urlssection getconfig () <br/>{< br/> return (urlss Ection) system. configuration. configurationmanager. getsection ("customconfiguration"); <br/>}</P> <p> public class urlssection: configurationsection <br/>{< br/> [configurationproperty ("URLs", isdefaultcollection = false)] <br/> Public urlscollection URLs <br/> {<br/> Get <br/> {<br/> return (urlscollection) This ["URLs"]; <br/>}</P> <p> // define the urlscollection that con Tains urlsconfigelement elements. <br/> public class urlscollection: configurationelementcollection <br/>{< br/> protected override configurationelement createnewelement () <br/>{< br/> return New urlconfigelement (); <br/>}< br/> protected override object getelementkey (configurationelement element) <br/>{< br/> return (urlconfigelement) element ). virtualurl; <br/>}</P> <p> Public urlconfigeleme Nt this [int Index] <br/> {<br/> Get <br/> {<br/> return (urlconfigelement) baseget (INDEX ); <br/>}</P> <p> // define the urlconfigelement. <br/> public class urlconfigelement: configurationelement <br/>{</P> <p> [configurationproperty ("virtualurl", isrequired = true)] <br/> Public String virtualurl <br/> {<br/> Get <br/> {<br/> return (string) This ["virtualurl"]; <br/>}< br/> S Et <br/> {<br/> This ["virtualurl"] = value; <br/>}</P> <p> [configurationproperty ("destinationurl", isrequired = true)] <br/> Public String destinationurl <br/> {<br/> Get <br/> {<br/> return (string) This ["destinationurl"]; <br/>}< br/> set <br/> {<br/> This ["destinationurl"] = value; <br/>}</P> <p> using system; <br/> using system. data; <br/> using system. configur Ation; <br/> using system. web; <br/> using system. web. security; <br/> using system. web. ui; <br/> using system. web. UI. webcontrols; <br/> using system. web. UI. webcontrols. webparts; <br/> using system. web. UI. htmlcontrols; </P> <p> /// <summary> <br/> // Summary of formrewriter <br/> /// </Summary> <br/> namespace urlrewriter. form <br/>{< br/> public class formrewritercontroladapter: system. web. UI. adapters. controlada Pter <br/>{< br/> Public formrewritercontroladapter () <br/>{< br/>}</P> <p> protected override void render (htmltextwriter writer) <br/>{< br/> base. render (New rewriteformhtmltextwriter (writer); <br/>}</P> <p> public class rewriteformhtmltextwriter: htmltextwriter <br/>{< br/> Public rewriteformhtmltextwriter (htmltextwriter writer) <br/>: Base (writer) <br/>{< br/> base. innerwriter = Writer. innerwriter; <br/>}< br/> Public rewriteformhtmltextwriter (system. io. textwriter writer) <br/>: Base (writer) <br/>{< br/> base. innerwriter = writer; <br/>}</P> <p> Public override void writeattribute (string name, string value, bool fencode) <br/> {<br/> // If the attribute we are writing is the "Action" attribute, and we are not on a sub-control, <br/> // then replace the value to write W Ith the raw URL of the request-which ensures that we'll <br/> // preserve the pathinfo value on PostBack scenarios <br/> If (name = "action ") <br/>{< br/> httpcontext context = httpcontext. current; <br/> If (context. items ["actionalreadywritten"] = NULL) <br/> {<br/> // we will use the request. rawurl property within ASP. net to retrieve the origional <br/> // URL before it was re-written. <br/> V Alue = context. request. rawurl; <br/> // indicate that we 've already rewritten the <form>'s action attribute to prevent <br/> // us from rewriting a sub-control under the <form> Control <br/> context. items ["actionalreadywritten"] = true; <br/>}< br/> base. writeattribute (name, value, fencode); <br/>}</P> <p> using system; <br/> using system. web; <br/> using system. text. regularexp Ressions; <br/> using system. configuration; <br/> using urlrewriter. config; </P> <p> namespace urlrewriter <br/> {<br/> public class rewritermodule: ihttpmodule <br/>{< br/> Public void Init (httpapplication APP) <br/>{< br/> // warning! This does not work with Windows Authentication! <Br/> // if you are using Windows authentication, change to app. beginrequest <br/> app. authorizerequest + = new eventhandler (this. urlrewriter); <br/>}</P> <p> protected void urlrewriter (Object sender, eventargs e) <br/>{< br/> httpapplication APP = (httpapplication) sender; <br/> string requestedpath = app. request. path; </P> <p> // get the configuration rules <br/> urlscollection rules = urlsconfig. Getconfig (). URLs; </P> <p> for (INT I = 0; I <rules. count; I ++) <br/>{< br/> // get the pattern to look for, and resolve the URL (convert ~ Into the appropriate directory) <br/> string lookfor = "^" + rewriterutils. resolveurl (App. context. request. applicationpath, rules [I]. virtualurl) + "$"; </P> <p> RegEx Re = new RegEx (lookfor, regexoptions. ignorecase); <br/> If (Re. ismatch (requestedpath) <br/>{< br/> string sendtourl = rewriterutils. resolveurl (App. context. request. applicationpath, re. replace (requestedpath, rules [I]. destinationurl); <B R/> rewriterutils. rewriteurl (App. context, sendtourl); <br/> break; <br/>}</P> <p> Public void dispose () {}< br/>}</P> <p> // <summary> <br/> // provides utility helper methods for the rewriting httpmodule and httphandler. <br/> /// </Summary> <br/> /// <remarks> this class is marked as internal, meaning only classes in the same assembly will be <br/> // able to access its meth ODS. </remarks> <br/> internal class rewriterutils <br/> {<br/> # region rewriteurl <br/> // <summary> <br/> /// rewrite's a URL using <B> httpcontext. rewriteurl () </B>. <br/> /// </Summary> <br/> /// <Param name = "context"> the httpcontext object to rewrite the URL. </param> <br/> // <Param name = "sendtourl"> the URL to rewrite. </param> <br/> internal static void rewriteurl (httpcontext context, S Tring sendtourl) <br/>{< br/> string X, Y; <br/> rewriteurl (context, sendtourl, out X, out y ); <br/>}</P> <p> // <summary> <br/> // rewrite's a URL using <B> httpcontext. rewriteurl () </B>. <br/> /// </Summary> <br/> /// <Param name = "context"> the httpcontext object to rewrite the URL. </param> <br/> // <Param name = "sendtourl"> the URL to rewrite. </param> <br/> // <Param name = "sendtourllessqs Tring "> returns the value of sendtourl stripped of the querystring. </param> <br/> // <Param name = "filepath"> returns the physical file path to the requested page. </param> <br/> internal static void rewriteurl (httpcontext context, string sendtourl, out string sendtourllessqstring, out string filepath) <br/>{< br/> // see if we need to add any extra querystring Information <br/> If (context. request. Querystring. Count> 0) <br/>{< br/> If (sendtourl. indexof ('? ')! =-1) <br/> sendtourl + = "&" + context. Request. querystring. tostring (); <br/> else <br/> sendtourl + = "? "+ Context. request. querystring. tostring (); <br/>}</P> <p> // first strip the querystring, if any <br/> string querystring = string. empty; <br/> sendtourllessqstring = sendtourl; <br/> If (sendtourl. indexof ('? ')> 0) <br/>{< br/> sendtourllessqstring = sendtourl. substring (0, sendtourl. indexof ('? '); <Br/> querystring = sendtourl. substring (sendtourl. indexof ('? ') + 1); <br/>}</P> <p> // grab the file's physical path <br/> filepath = string. empty; <br/> filepath = context. server. mappath (sendtourllessqstring); </P> <p> // rewrite the path <br/> context. rewritepath (sendtourllessqstring, String. empty, querystring ); <br/>}< br/> # endregion </P> <p> // <summary> <br/> // converts a URL into one that is usable on the requesting client. <br/> // </Summary> <br/> /// <Remarks> converts ~ To the requesting Application Path. mimics the behavior of the <br/> // <B> control. resolveurl () </B> method, which is often used by control developers. </remarks> <br/> // <Param name = "apppath"> the Application Path. </param> <br/> // <Param name = "url"> the URL, which might contain ~. </Param> <br/> // <returns> A resolved URL. If the input parameter <B> URL </B> contains ~, It is replaced with the <br/> // value of the <B> apppath </B> parameter. </returns> <br/> internal static string resolveurl (string apppath, string URL) <br/>{< br/> If (URL. length = 0 | URL [0]! = '~ ') <Br/> return URL; // There is no ~ In the first character position, just return the URL <br/> else <br/>{< br/> If (URL. length = 1) <br/> return apppath; // There is just ~ In the URL, return the apppath <br/> If (URL [1] = '/' | URL [1] = '//') <br/> {<br/> // URL looks like ~ /Or ~ /<Br/> If (apppath. length> 1) <br/> return apppath + "/" + URL. substring (2); <br/> else <br/> return "/" + URL. substring (2); <br/>}< br/> else <br/> {<br/> // URL looks like ~ Something <br/> If (apppath. length> 1) <br/> return apppath + "/" + URL. substring (1); <br/> else <br/> return apppath + URL. substring (1); <br/>}</P> <p>
2. Set the following in Web. config: </P> <p> Code <br/> <? XML version = "1.0"?> <Br/> <configuration> <br/> <configsections> <br/> <section name = "customconfiguration" type = "urlrewriter. config. urlssection, urlrewriter "/> <br/> </configsections> </P> <p> <customconfiguration> <br/> <URLs> <br/> <add virtualurl = "~ /Microsoft *. * "destinationurl = "~ /Default. aspx? Id = ABC "/> <br/> <add virtualurl = "~ /Microsoft * "destinationurl = "~ /Default. aspx "/> <br/> <add virtualurl = "~ /M/I/c/rosoft. aspx "destinationurl = "~ /Default. aspx "/> </P> <p> <add virtualurl = "~ /CC *. * "destinationurl = "~ /Default2.aspx? Id = 11 "/> <br/> </URLs> <br/> </customconfiguration> </P> <p> <system. web> <br/> <pttpmodules> <br/> <add type = "urlrewriter. rewritermodule, urlrewriter "name =" rewritermodule "/> <br/> </pttpmodules> <br/> <Authentication mode =" forms "/> <br/> </system. web> <br/> </configuration> </P> <p> 3. process sending back <br/> If a sending back is generated in the rewritten URL, for example, there is a button that calls the overwritten aspx, the actual address of the aspx file is displayed in the user's browser, that is, http: // hostname/default. aspx? Id = 11. But from the user's point of view, if you suddenly see the URL change when you click the button, it will make them feel uneasy. Therefore, this problem must be solved. <Br/> define an actionlessform class by yourself and no longer use the form flag provided by the system in aspx </P> <p> Code <br/> using system; <br/> using system. web. ui; <br/> using system. web. UI. webcontrols; <br/> using system. componentmodel; </P> <p> namespace actionlessform <br/> {<br/> /// <summary> <br/> // The Form class extends the htmlform HTML control overriding its renderattributes () <br/> // method and not emitting an action attribute. <br/> /// </s Ummary> <br/> public class form: system. web. UI. htmlcontrols. htmlform <br/> {<br/> /// <summary> <br/> // The renderattributes method adds the attributes to the rendered <form> tag. <br/> // we override this method so that the action attribute is not emitted. <br/> // </Summary> <br/> protected override void renderattributes (htmltextwriter writer) <br/>{< br/> // write the form's name <br/> W Riter. writeattribute ("name", this. name); <br/> base. attributes. remove ("name"); </P> <p> // write the form's method <br/> writer. writeattribute ("method", this. method); <br/> base. attributes. remove ("method"); </P> <p> // remove the action attribute <br/> base. attributes. remove ("action"); </P> <p> // finally write all other attributes <br/> This. attributes. render (writer); </P> <p> If (base. ID! = NULL) <br/> writer. writeattribute ("ID", base. clientid); <br/>}</P> <p >}< br/>}</P> <p> after creating and compiling this class, in ASP. to use it in a web application, you must first add it to the references folder of the Web application. Then, you need to use it to replace the htmlform class. The practice is in ASP. </P> <p> <% @ register tagprefix = "af" namespace = "actionlessform" assembly = "actionlessform" %>
Example download: urlrewriter.rar
If the file cannot be found, go to IIS -- main directory -- configuration -- -- insert C:/Windows/microsoft.net/framework/v2.0.50727/aspnet_isapi.dllto remove the "check whether the file exists" option box and click OK.