The URL rewriting technology is no longer a new topic today. On the Apache server, the URL rewriting module named mod_rewrite is provided, while on the IIS server, there are also many commercial ISAPI filter modules available. However, we do not have a lot of funds or shared servers, which makes the above methods not the best solution. Fortunately, ASP. NET provides us with powerful scalability, allowing us to customize page access rules and easily implement URL rewriting.
- Download the sample code in this article
To implement URL rewriting in ASP. NET, you need to create an HTTP module or an HTTP handler (httphandler) and call the rewritepath method of httpcontext to perform URL rewriting. This article uses the HTTP module as an example.
Use the HTTP module to perform URL rewriting
First, define a class that implements the ihttpmodule interface. The ihttpmodule interface defines two methods to be implemented:
- Init (httpapplication ). This method is triggered after the HTTP module is initialized. In this method, you will bind the event handler to the corresponding httpapplication event.
- Dispose (). This method is called when the request is complete and has been sent back to IIS. You shall perform all final cleanup operations here.
1: public virtual void Init(HttpApplication app)
2: {
3: // WARNING! This does not work with Windows authentication!
4: // If you are using Windows authentication, change to app.BeginRequest
5: app.AuthorizeRequest += new EventHandler(this.URLRewriter);
6: }
Note::If you want to use form authentication instead of Windows authentication, rewrite the URL and run it in the authorizerequest event handler. If you want to use Windows authentication, arrange URL rewriting during the beginrequest or authenticaterequest event.
The second line in the urlrewriter method reads URL rewriting information from the configuration file for processing, such as regular expression processing. If you are not clear about how to expand the standard configuration file, please refer to this blog: Expand the. NET 2.0 standard configuration file.
1: protected void URLRewriter(object sender, EventArgs e)
2: {
3: HttpApplication app = (HttpApplication) sender;
4: string requestedPath = app.Request.Path;
5:
6: // get the configuration rules
7: UrlsCollection rules = UrlsConfig.GetConfig().Urls;
8:
9: for (int i = 0; i < rules.Count; i++)
10: {
11: // get the pattern to look for, and Resolve the Url (convert ~ into the appropriate directory)
12: string lookFor = "^" + RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, rules[i].VirtualUrl) + "$";
13:
14: Regex re = new Regex(lookFor, RegexOptions.IgnoreCase);
15: if (re.IsMatch(requestedPath))
16: {
17: string sendToUrl = RewriterUtils.ResolveUrl(app.Context.Request.ApplicationPath, re.Replace(requestedPath, rules[i].DestinationUrl));
18: RewriterUtils.RewriteUrl(app.Context, sendToUrl);
19: break;
20: }
21: }
22:
23: }
If yes, call the rewriteurl method to break down the URL into two parts: the path and the query string, and call httpcontext. rewritepath to rewrite the URL. The "Additional URL path information" (for example, the tail part of http: // www.microsoft.com/virdir/page.html/tail) is not processed, and the string is used directly. empty. You can expand it as needed.
OK, so far, a simple URL rewriting program has been initially completed, but it has not been completed yet. We need to solve the problem of details, that is, after the page is sent back, the address before rewriting will be displayed in the address bar, that is, the real address, affecting the appearance of the image :). There are two ways to solve this problem:
- Customize a control that inherits the Form Control
1: public class Form : System.Web.UI.HtmlControls.HtmlForm
2: {
3: /// <summary>
4: /// The RenderAttributes method adds the attributes to the rendered <form> tag.
5: /// We override this method so that the action attribute is not emitted.
6: /// </summary>
7: protected override void RenderAttributes(HtmlTextWriter writer)
8: {
9: // write the form's name
10: writer.WriteAttribute("name", this.Name);
11: base.Attributes.Remove("name");
12:
13: // write the form's method
14: writer.WriteAttribute("method", this.Method);
15: base.Attributes.Remove("method");
16:
17: // remove the action attribute
18: base.Attributes.Remove("action");
19:
20: // finally write all other attributes
21: this.Attributes.Render(writer);
22:
23: if (base.ID != null)
24: writer.WriteAttribute("id", base.ClientID);
25: }
26:
27: }
This method directly removes the form action attribute, so the page is directly sent back to itself, which can solve the problem, but it is troublesome to use. Imagine you have to rewrite the form mark on every page that requires URL rewriting, which is enough to crash.
- Custom Control Output Using ASP. NET 2.0 control adapter extension Architecture
In ASP. NET 2.0, there is a cleaner trick that can be used to override the action attribute of the <form> control. Specifically, the new ASP. NET 2.0 control adapter extension architecture is used to customize the control output, and the provided value is used to overwrite the value of the action attribute. This does not require any encoding changes on the. ASPX page, but you only need to add a. Browser file in the/app_browsers folder and register a control adaptation class to output new Action attributes.
. Browser file
1: <browsers>
2: <browser refID="Default">
3: <controlAdapters>
4: <adapter controlType="System.Web.UI.HtmlControls.HtmlForm"
5: adapterType="URLRewriter.Form.FormRewriterControlAdapter" />
6: </controlAdapters>
7: </browser>
8: </browsers>
Urlrewriter. Form. CS File
1: public class FormRewriterControlAdapter : System.Web.UI.Adapters.ControlAdapter
2: {
3: public FormRewriterControlAdapter()
4: {
5: }
6:
7: protected override void Render(HtmlTextWriter writer)
8: {
9: base.Render(new RewriteFormHtmlTextWriter(writer));
10: }
11: }
12:
13: public class RewriteFormHtmlTextWriter : HtmlTextWriter
14: {
15: public RewriteFormHtmlTextWriter(HtmlTextWriter writer)
16: : base(writer)
17: {
18: base.InnerWriter = writer.InnerWriter;
19: }
20: public RewriteFormHtmlTextWriter(System.IO.TextWriter writer)
21: : base(writer)
22: {
23: base.InnerWriter = writer;
24: }
25:
26: public override void WriteAttribute(string name, string value, bool fEncode)
27: {
28: //If the attribute we are writing is the "action" attribute, and we are not on a sub-control,
29: //then replace the value to write with the raw URL of the request - which ensures that we'll
30: //preserve the PathInfo value on postback scenarios
31: if (name == "action")
32: {
33: HttpContext context = HttpContext.Current;
34: if (context.Items["ActionAlreadyWritten"] == null)
35: {
36: //We will use the Request.RawUrl property within ASP.NET to retrieve the origional
37: //URL before it was re-written.
38: value = context.Request.RawUrl;
39: //Indicate that we've already rewritten the <form>'s action attribute to prevent
40: //us from rewriting a sub-control under the <form> control
41: context.Items["ActionAlreadyWritten"] = true;
42: }
43: }
44: base.WriteAttribute(name, value, fEncode);
45: }
46: }
It is simple and cost-effective to directly assign the value of the action attribute to the address after URL rewriting. Why not.
Correction:Because I did a direct test in Vs, I used the lightweight server that comes with vs (ASP. NET development server) instead of the IIS. With the message from Brother Liu Dao, I saw the reprinted 51aspx and corrected this error. Thank you.
After testing in IIS, it is found that the custom URL suffix needs to be mapped to aspnet_isapi.dll in IIS, I guess in the Development Server, all suffixes should be mapped to aspnet_isapi.dll. Therefore, if your space is in a shared environment and is not easy to modify, it is also a good way to directly use aspx as the suffix.
References:
- Httpcontext. rewritepath on msdn
- Tip/tip: rewrite a URL in ASP. NET
- Execute URL rewriting in ASP. NET