URL rewriting in asp.net 2.0 and urlmappings problem _ practical Tips

Source: Internet
Author: User
Tags flush httpcontext
In the asp.net2.0 of urlmappings is very useful, but temporarily does not support regular expression, but, fortunately, if the ihttpmodule words

No matter what kind of request goes through IHttpModule First, this provides a good opportunity for URL rewriting:

Here's a ihttpmodule I wrote:

Using System;
Using System.Web;

public class Rewritemodule:ihttpmodule
{
Public Rewritemodule ()
{
}
public override string ToString ()
{
return this. GetType (). ToString ();
}


void Ihttpmodule.dispose ()
{

}
private static System.Xml.XmlDocument Ruledoc = null;
private static System.Xml.XmlDocument Getruleconfig (System.Web.HttpContext app)
{
if (Ruledoc = null)
{
Ruledoc = new System.Xml.XmlDocument ();
Ruledoc.load (app. Server.MapPath ("~/rule.xml"));
}
return ruledoc;
}
public static string GetUrl (System.Web.HttpContext cxt,string path)
{

System.Xml.XmlDocument doc = Getruleconfig (CXT);
System.Xml.XmlNodeList lst= Doc. getElementsByTagName ("Rewriterrule");
String pat= "";
foreach (System.Xml.XmlNode nd in LST)
{
System.Xml.XmlNodeList sub = nd. Childnodes[0]. ChildNodes;
foreach (System.Xml.XmlNode chk in sub)
{
Pat = "^" + chk. innertext+ "$";
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex (PAT, System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (Reg. IsMatch (PATH))
{
Return Reg. Replace (Path, ND. CHILDNODES[1]. InnerText);
}
}
}
return null;

}
void Ihttpmodule.init (HttpApplication context)
{
Context. BeginRequest + = Delegate (object sender, EventArgs e)
{


System.Web.HttpContext CXT = context. context;

if (CXT. Request.contenttype!= "Image/pjpeg")
{
String type = Cxt. Request.ContentType.ToLower ();
String path = Cxt. Request.path;
String AppPath = Cxt. Request.applicationpath;
Path = path. Remove (0, AppPath. Length);
Path = "~" + path;

String newurl = GetUrl (cxt, path. TrimEnd (). TrimStart ());
if (Newurl!= null)
{
Cxt. Response.filter = new Responsefilter (CXT. Response.filter,cxt. Request.path);
Cxt. Response.Write ("Path of the request:" + path);
Cxt. Response.Write ("<BR>");
Cxt. Response.Write ("The purpose of the steering URL:" + newurl);
Cxt. Response.Write ("<BR>");
Cxt. RewritePath (Newurl);



}//If you require all requests to be processed
Else
//{
Cxt. Response.Write (CXT. Request.path + "<BR>");
Cxt. Response.Write ("The resources you requested do not exist or have no access!") ");
Cxt. Response.Flush ();
Cxt. Response.End ();
//}
}

};
}
}

Because once the URL is rewritten, the action in the original WebForm changes, which is easy: the requested resource does not have a problem

How exactly? I'll see you in DX,!!!.

All this responsefilter has been achieved, as follows,

public class ResponseFilter:System.IO.Stream
{
Public Responsefilter (System.IO.Stream sink,string _str)
{
_sink = sink;
//
TODO: Add constructor logic here
//
This.str = _str;
}
private string str = "";
Private System.IO.Stream _sink;
Private long _position;
Private System.Text.Encoding end=system.text.encoding.getencoding ("GB18030");
Private System.Text.StringBuilder ooutput = new System.Text.StringBuilder ();
The following members of the Stream must are overriden.
public override bool CanRead
{
get {return true;}
}

public override bool CanSeek
{
get {return true;}
}

public override bool CanWrite
{
get {return true;}
}

public override Long Length
{
get {return 0;}
}

public override Long Position
{
get {return _position;}
set {_position = value;}
}

public override long (long offset, System.IO.SeekOrigin direction)
{
Return _sink. Seek (offset, direction);
}

public override void SetLength (long length)
{
_sink. SetLength (length);
}

public override void Close ()
{
_sink. Close ();
}

public override void Flush ()
{
_sink. Flush ();
}

public override int Read (byte[] buffer, int offset, int count)
{
Return _sink. Read (buffer, offset, count);
}

The Write method actually does the filtering.
public override void Write (byte[] buffer, int offset, int count)
{
String szbuffer = System.Text.UTF8Encoding.UTF8.GetString (buffer, offset, count);
String ap= "action=\";
int pos=-1;
if ((Pos=szbuffer.indexof (AP))!=-1)
{
int epos = Szbuffer.indexof ("\"), POS + AP. LENGTH+1);
if (Epos!=-1)
{
Szbuffer= szbuffer.remove (pos + AP. Length, Epos-pos-ap. Length);
}

Szbuffer = Szbuffer.insert (pos + AP. Length, THIS.STR);

byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes (szbuffer);
_sink. Write (data, 0, data. Length);

}
Else
{
Ooutput.append (Szbuffer);
}

The following paragraph can be used to modify the content between <Head>Regex oendfile = new Regex ("if (Oendfile.ismatch (szbuffer))
//{
Append the last buffer of data
Append last piece of data from the upper buffer
Ooutput.append (Szbuffer);
Get back the complete response for the client
Returns the full client return data
String szcompletebuffer = Ooutput.tostring (). ToLower ();
int ipos = Szcompletebuffer.indexof ("<title>");
int epos = Szcompletebuffer.indexof ("</title>", ipos+7);
String sp = Szcompletebuffer.substring (ipos+7, Epos-ipos);
Szcompletebuffer = Szcompletebuffer.remove (ipos+7,sp. LENGTH-7);
Szcompletebuffer = Szcompletebuffer.insert (ipos + 7, "dhz");
Szcompletebuffer = Szcompletebuffer.replace (sp, "dhz");
No match, so write out original data
No match, so write source code
byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes (Szcompletebuffer);
_sink. Write (data, 0, data. Length);
//}
Else
//{
Ooutput.append (Szbuffer);
//}
}
}

And the heavy-weather rules are configured with XML files as follows;

Of course, it's OK to do it in Web.config by customizing the configuration section.

<?xml version= "1.0" encoding= "Utf-8"?>
<Rules>
<RewriterRule>
<LookFors>
<lookfor>~/(\d{4})/(\d{2}) \.html</lookfor>
<lookfor>~/(\d{4})/(\d{2})/</lookfor>
<lookfor>~/(\d{4})/(\d{2}) </LookFor>
<lookfor>~/(\d{4})/(\d{2})/index.html</lookfor>
</LookFors>
<SendTo>~/Pro.aspx?year=$1&month=$2</SendTo>
</RewriterRule>
<RewriterRule>
<LookFors>
<LookFor>~/pc</LookFor>
</LookFors>
<SendTo>~/Test2.aspx</SendTo>
</RewriterRule>
</Rules>
This rule is poorly written, as the first one can be done with a regular expression.
Related Article

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.