Realizing Urlrewrite with Asp.net on Virtual Host

  
                  Seen on the Internet, many friends do urlrewrite in asp.net, using the HttpHandle+Server.Transfer method. In fact, this method is wrong. First, HttpHandle can't implement urlrewrite; the second Server.Transfer is a standard redirect, not urlrewrite at all.

In fact, do not have to achieve urlrewrite HttpHandle, they do not achieve their own HttpModule, with a few lines of code can be easily achieved.

I am introducing here on the virtual host, the virtual host is different from the server of your own, you do not have the right to modify IIS, and do not have permission to install IIS plugin such as iis rewrite. But we can still easily complete the functions we need.

Specifically, the following: open global.asax.cs, targeting protected void Application_BeginRequest (Object sender, EventArgs e). I can guess what it is from the method name. Enter the following code:


 protected void Application_BeginRequest (Object sender, EventArgs e) 
{string oldUrl = HttpContext.Current.Request.RawUrl;
string pattern = @ "^ (.+)default/(\\d+)\\.aspx(\\?.*)*___FCKpd___0quot;;
string replace = "$1default.aspx?id=$2"; if(Regex.IsMatch(oldUrl,
pattern, RegexOptions.IgnoreCase RegexOptions.Compiled))
{ string newUrl = Regex.Replace(oldUrl, pattern, replace,
RegexOptions.Compiled RegexOptions.IgnoreCase);
this.Context.RewritePath(newUrl) ; }}


With the above code, I visit a URL like: .../default/123.aspx, of course this URL does not exist on my computer, it will Is directed to: .../default.aspx?id=123.

Of course, with powerful regular expressions, you can override the url as you like, all in the server The silent process, there will be no notice on the client. Because it is on the virtual host, We can only redirect the .aspx file. If it is our own server, you can implement any suffix name by registering the suffix name in IIS. For example, you can register a type such as *.myweb so that others can access the default. /456.myweb, you can redirect it to default.aspx?id=456. In a word, as long as you can think of .net can help you achieve, and this does not require much code.
Copyright © Windows knowledge All Rights Reserved