How to use asp.net Urlrewriter on a virtual host

  • 2020-05-07 19:29:00
  • OfStack

First, HttpHandle cannot implement urlrewrite;
Server.Transfer is a standard redirect, not urlrewrite at all.
In fact, urlrewrite does not need to implement HttpHandle itself, nor does it need to implement HttpModule itself, which can be easily implemented in a few lines of code.
What I introduce here is on the virtual host, the virtual host is different from their own server, you are not authorized to modify IIS, also do not have the authorization to install iis rewrite such as IIS plug-in. But we can still do what we need easily.
Here's how: open global.asax.cs and navigate to protected void Application_BeginRequest(Object sender, EventArgs e). From the method name, I guess I can guess what it does. Enter the following code:
 
protected void Application_BeginRequest(Object sender, EventArgs e) 
{ 
string oldUrl = HttpContext.Current.Request.RawUrl ; 
string pattern = @"^(.+)default/(\d+)\.aspx(\?.*)*$"; 
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 access a similar:... /default/ 123.aspx, which of course does not exist on my computer, will be directed to:... 1 / default aspx? id = 123.
Of course, with powerful regular expressions, you can rewrite url as you want,
This is all done silently on the server side, without any awareness on the client side. Because it is on the virtual host, we can only redirect.aspx file, if it is their own server, as long as the suffix name in IIS registered 1, you can achieve any suffix name processing. For example, you can register a *.myweb type so that when someone accesses default/ 456.myweb, you can redirect it to default.aspx? id = 456. All in all, 1 sentence, as long as you can think of.net can help you to implement, and this 1 cut does not need much code.

Related articles: