Implement a fast, simple and efficient URL rewrite scheme with flexible configuration

Source: Internet
Author: User
Tags foreach bool empty httpcontext implement url example

Need source code please leave an email in the comments

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 properties and methods
String siteurlsfile = HttpContext.Current.Server.MapPath (configurationsettings.appsettings["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 (url = 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 Variable
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 Constructors
Public Urlrewrite (string name, string pattern, String page, String querystring)
{
_name = Name;
_pattern = pattern;
_page = Page;
_querystring = querystring;
}
#endregion
}

public class Pagebase:page
{
Private Pagebase ()
{
//
TODO: Add constructor logic here
//
}

<summary>
Overrides the default HtmlTextWriter method, modifying the Value property in the form tag so that its value is the overridden 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; Fake 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 property is a form-marked Action property, the value is replaced with the overridden 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);
}
}

To override a configuration file:

<?xml version= "1.0" encoding= "Utf-8"?>
<SiteUrls>
<!--If you rewrite the shtml extension, you need to adjust the application mappings in IIS, mapping the shtml extension to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\aspnet_ Isapi.dll, be aware that canceling the check file exists-->
<!--access mode http://localhost/Example/Show/323.shtml-->
<rewrite name= "Show"
Path= "/show/{0}.shtml"
Pattern = "/show/(\d+). shtml"
Page= "/webform1.aspx"
querystring= "Id=$1^cn=itemlist"/>

</SiteUrls>



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.