URL rewriting in ASP. NET

Source: Internet
Author: User
URL rewriting is to rewrite the URL address (Khan _ ^ ).

Details: http://www.microsoft.com/china/msdn/library/webservices/asp.net/URLRewriting.mspx

Advantage: shorten the URL.

Usage: 1. Download the MS urlrewrite. dll and put it in your bin.

2. Set the following in Web. config:

<? XML version = "1.0" encoding = "UTF-8"?>
<Configuration>

<Configsections>

<Section name = "rewriterconfig" type = "urlrewriter. config. rewriterconfigserializersectionhandler, urlrewriter"/>

</Configsections>

<Rewriterconfig>

<Rules>

<Rewriterrule>
<Lookfor> ~ /D (\ D +) \. aspx </lookfor>
<Sendto> ~ /Default. aspx? Id = $1 </sendto>
</Rewriterrule>

</Rules>

</Rewriterconfig>

<System. Web>

<Httphandlers>

<Add verb = "*" Path = "*. aspx"

Type = "urlrewriter. rewriterfactoryhandler, urlrewriter"/>

</Httphandlers>

Then write in Cs:

Private void page_load (Object sender, system. eventargs E)
{
// Place the user hereCodeTo initialize the page
Response. Write (request. querystring ["ID"] + "<br> ");
Response. Write ("Haha ");
}

Just enter

Localhost/overred/d123.aspx (Note: it must start with D and end with a number)
In fact, this d123.aspx is virtual and does not actually exist. You only need to conform to the format.

It will jump to http: // localhost/overred/default. aspx

In addition, it can capture some parameters such as ID in default, that is, the number after your D (must be a number later), so that you can display the value of ID 123Article.

If a response is generated in the URL after rewriting, it will be passed to d123.aspx, so that the user can see the actual address when clicking the button, as described in msdn: but from the user's perspective, if you suddenly see a URL change when you click the button, they will feel uneasy.

It can be seen that Ms holds the customer as his god! (True? # ¥ % ...... -*)

Continue to reference MS:

The reason for this is that when a web form is displayed, it directly sets its operation attribute to the file path value in the request object. Of course, when rendering a web form, the URL has been rewritten from/products/beverages. aspx to listproductsbycategory. aspx? Categoryid = 1, which indicates that the request object reports that the user wants to access listproductsbycategory. aspx? Categoryid = 1. This problem can be solved simply by making the server-side form not present operation properties. (By default, if the form does not contain operation attributes, the browser will send back .)

Unfortunately, the web form does not allow you to explicitly specify operation properties or set certain properties to disable the rendering of operation properties. Therefore, we must extend the system. Web. htmlcontrols. htmlform class by ourselves to overwrite the renderattribute () method and explicitly state that it will not render the operation attribute.

Because of the inheritance function, we can obtain all the functions of the htmlform class, and only need to add a few lines of code to obtain the required behavior. The complete code for the custom class is shown below:

Namespace actionlessform {
Public class form: system. Web. UI. htmlcontrols. htmlform
{
Protected override void renderattributes (htmltextwriter writer)
{
Writer. writeattribute ("name", this. Name );
Base. Attributes. Remove ("name ");

Writer. writeattribute ("method", this. method );
Base. Attributes. Remove ("method ");

This. Attributes. Render (writer );

Base. Attributes. Remove ("action ");

If (base. ID! = NULL)
Writer. writeattribute ("ID", base. clientid );
}
}
}

The code of the overwritten renderattributes () method only contains the accurate code of the renderattributes () method of the htmlform class, without setting the operation attribute. (I use Lutz roeder's reflector to viewSource code.)

After this class is created and compiled, it must be applied to ASP. NET web applications.ProgramTo use it, you must first add it to the references folder of the Web application. Then, to use it to replace the htmlform class, you only need to add the following content to the top of the ASP. NET webpage:

<% @ Register tagprefix = "SKM" namespace = "actionlessform"
Assembly = "actionlessform" %>

Then, replace <form runat = "server"> (if any):

<SKM: Form ID = "form1" method = "Post" runat = "server">

And replace the </form> mark on the right:

</SKM: Form>

The above is to inherit a form. In fact, it is simpler to inherit the page, so you do not need to modify anything on the ASPX page.
Code:
Using system;
Using system. IO;
Using system. Web;
Using system. Web. UI;

Namespace URL
{
/** // <Summary>
/// Page base class www.knowsky.com
/// </Summary>
Public class olpage: Page
{
Public olpage ()
{
}

/** // <Summary>
/// Rewrite the default htmltextwriter method, modify the value attribute in the form tag, and set the value to the rewritten URL instead of the real URL.
/// </Summary>
/// <Param name = "Writer"> </param>
Protected override void render (htmltextwriter writer)
{

If (writer is system. Web. UI. html32textwriter)
{
Writer = new formfixerhtml32textwriter (writer. innerwriter );
}
Else
{
Writer = new formfixerhtmltextwriter (writer. innerwriter );
}

Base. Render (writer );
}

}

Internal class formfixerhtml32textwriter: system. Web. UI. html32textwriter
{
Private string _ URL; // a false URL

Internal formfixerhtml32textwriter (textwriter writer): Base (writer)
{
_ Url = httpcontext. Current. Request. rawurl;
}

Public override void writeattribute (string name, string value, bool encode)
{
// If the current output attribute is the form-marked action attribute, replace the value with the rewritten false URL
If (_ URL! = NULL & string. Compare (name, "action", true) = 0)
{
Value = _ URL;
}
Base. writeattribute (name, value, encode );
}
}

Internal class formfixerhtmltextwriter: system. Web. UI. htmltextwriter
{
Private string _ URL;
Internal formfixerhtmltextwriter (textwriter writer): Base (writer)
{
_ Url = httpcontext. Current. Request. rawurl;
}

Public override void writeattribute (string name, string value, bool encode)
{
If (_ URL! = NULL & string. Compare (name, "action", true) = 0)
{
Value = _ URL;
}

Base. writeattribute (name, value, encode );
}
}

}

You can encapsulate it as a DLL and add references later!

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.