A simple and efficient URL rewriting solution with flexible configuration (with source code)

Source: Internet
Author: User
Tags url example

Download Code: http://www.ssxz.com/iuhxq/index.html

By referencing urlrewrite. dll, you only need to add two lines to rewrite the URL.

Key code:
Public class myhttpmodule: ihttpmodule
{
Public void Init (httpapplication APP)
{
App. authorizerequest + = new eventhandler (app_authorizerequest );
}

Public void dispose (){}

Protected void rewrite (string requestedpath, system. Web. httpapplication APP)
{
// App. Context. rewritepath ("~ /Default. aspx ", String. Empty," test = tttttttt ");
Foreach (urlrewrite URL in siteurls. getsiteurls (). URLs)
{
If (RegEx. ismatch (App. Context. Request. Path, URL. pattern, regexoptions. Compiled | regexoptions. ignorecase ))
{
App. context. rewritepath (URL. page, String. empty, RegEx. replace (App. context. request. path, URL. pattern, URL. querystring, regexoptions. compiled | regexoptions. ignorecase ));
Return;
}
}
If (App. Context. Request. Path. tolower (). endswith (". shtml "))
{
App. Context. response. Redirect ("~ /Index.html ");
}
}

Private void app_authorizerequest (Object sender, eventargs E)
{
Httpapplication APP = (httpapplication) sender;
Rewrite (App. Request. Path, APP );
}
}

Public class siteurls
{
# Region internal attributes and Methods
String siteurlsfile = httpcontext. Current. server. mappath (configurationsettings. deleettings ["siteurls"]);
Private arraylist _ URLs;
Public arraylist URLs
{
Get
{
Return _ URLs;
}
Set
{
_ URLs = value;
}
}

Private namevaluecollection _ paths;
Public namevaluecollection paths
{
Get
{
Return _ paths;
}
Set
{
_ Paths = value;
}
}

Private siteurls ()
{
String applicationpath = httpcontext. Current. Request. applicationpath;

If (applicationpath = "/")
{
Applicationpath = string. empty;
}

URLs = new arraylist ();
Paths = new namevaluecollection ();
Paths. Add ("home", applicationpath );

Xmldocument xml = new xmldocument ();

XML. Load (siteurlsfile );

Xmlnode root = xml. selectsinglenode ("siteurls ");
Foreach (xmlnode N in root. childnodes)
{
If (N. nodetype! = Xmlnodetype. Comment & N. Name. tolower () = "Rewrite ")
{
Xmlattribute name = n. attributes ["name"];
Xmlattribute Path = n. attributes ["path"];
Xmlattribute page = n. attributes ["page"];
Xmlattribute querystring = n. attributes ["querystring"];
Xmlattribute pattern = n. attributes ["pattern"];

If (name! = NULL & path! = NULL & page! = NULL & querystring! = NULL & pattern! = NULL)
{
Paths. Add (name. Value, applicationpath + path. value );
URLs. add (New urlrewrite (name. value, paths ["home"] + pattern. value, paths ["home"] + Page. value. replace ("^", "&"), querystring. value. replace ("^ ","&")));
}
}
}
}
# Endregion

Public static siteurls getsiteurls ()
{
String cachekey = "siteurls ";
Siteurls URLs = system. Web. httpcontext. Current. cache ["siteurls"] As siteurls;
If (URLs = NULL)
{
URLs = new siteurls ();
System. Web. httpcontext. Current. cache. insert (cachekey, URLs, new cachedependency (URLs. siteurlsfile), datetime. maxvalue, timespan. Zero, cacheitempriority. High, null );
}

Return URLs;
}

/// <Summary>
/// Output URL example
/// </Summary>
/// <Param name = "ID"> </param>
/// <Returns> </returns>
Public String show (int id)
{
Return string. Format (paths ["show"], ID );
}

Public class urlrewrite
{
# Region member variables
Private string _ name;
Public string name
{
Get
{
Return _ name;
}
Set
{
_ Name = value;
}
}

Private string _ pattern;
Public String Pattern
{
Get
{
Return _ pattern;
}
Set
{
_ Pattern = value;
}
}

Private string _ page;
Public String page
{
Get
{
Return _ page;
}
Set
{
_ Page = value;
}
}

Private string _ querystring;
Public String querystring
{
Get
{
Return _ querystring;
}
Set
{
_ Querystring = value;
}
}
# Endregion

# Region Constructor
Public urlrewrite (string name, string pattern, string page, string querystring)
{
_ Name = Name;
_ Pattern = pattern;
_ Page = page;
_ Querystring = querystring;
}
# Endregion
}

Public class pagebase: Page
{
//// <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 );
}
}

Rewrite the configuration file:

<? XML version = "1.0" encoding = "UTF-8"?>
<Siteurls>
<! -- If you want to override the shtml extension, you need to adjust the application ing in IIS to map the shtml extension to C:/Windows/Microsoft. net/framework/v1.1.4322/aspnet_isapi.dll. Check whether the file exists. -->
<! -- Access method http: // localhost/example/show/323.shtml -->
<Rewrite name = "show"
Path = "/show/clusters 02.16.shtml"
Pattern = "/show/(/d1_0000.shtml"
Page = "/webform1.aspx"
Querystring = "id = $1 ^ Cn = itemlist"/>

</Siteurls>

Add the following content to Web. config:

<Deleetask>
<Add key = "siteurls" value = "~ /Siteurls. config "/>
</Appsettings>

<Httpmodules>
<Add name = "myhttpmodule" type = "urlrewrite. myhttpmodule, urlrewrite"/>
</Httpmodules>

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.