I saw on the Internet that many friends do urlrewrite in asp.net and use the HttpHandle+Server.Transfer method. In fact, this method is wrong. First, HttpHandle cannot implement urlrewrite; secondly, Server.Transfer is a standard redirection, not urlrewrite at all.
In fact, you don't need to implement your own HttpHandle or HttpModule to implement urlrewrite. It can be easily implemented with a few lines of code.
What I am introducing here is on a virtual host. The virtual host is different from your own server. You do not have the permission to modify iis, nor do you have the permission to install iis plug-ins such as iis rewrite. But we can still easily complete the required functions.
The specific method is as follows: Open global.asax.cs and locate protected void Application_BeginRequest(Object sender, EventArgs e). From the method name, I think 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 URL similar to: .../default/123.aspx. Of course, this URL does not exist on my computer, so it will be directed to: .../default.aspx? id=123.
Of course, using powerful regular expressions, you can rewrite the URL according to your own needs. All this is done silently on the server side, and the client will not be aware of it. Since it is on a virtual host, we can only redirect the .aspx file. If it is our own server, we can process any suffix by just registering the suffix in iis. For example, you can register a type like *.myweb, so that when others visit default/456.myweb, you can redirect it to default.aspx?id=456. In a word, as long as you can think of it, .net can help you realize it, and all this does not require much code.