Use Application_BeginRequest of Global. asax to implement url rewriting without a suffix
Copy codeThe Code is as follows:
<% @ Application Language = "C #" %>
<Script RunAt = "server">
Void Application_BeginRequest (object sender, EventArgs e)
{
String oldUrl = System. Web. HttpContext. Current. Request. RawUrl; // get the initial url
//~ /123. aspx → ~ /Index. aspx? Id = 123
Regex reg = new Regex (@ "^ \/\ d + \. html ");
If (reg. IsMatch (oldUrl ))
{
String id = reg. Match (oldUrl). ToString (). Substring (1, reg. Match (oldUrl). ToString (). LastIndexOf (".")-1 );
Context. RewritePath ("~ /Index. aspx? Id = "+ id );
}
//~ /123 → ~ /Index. aspx? Id = 123
Regex reg1 = new Regex (@ "^ \/\ d + $ ");
If (reg1.IsMatch (oldUrl ))
{
String id = reg1.Match (oldUrl). ToString (). Substring (1 );
Context. RewritePath ("~ /Index. aspx? Id = "+ id );
}
//~ /Index/123 → ~ /Index. aspx? Id = 123
Regex reg3 = new Regex (@ "^ \/index \/\ d + $ ");
If (reg3.IsMatch (oldUrl ))
{
String id = reg3.Match (oldUrl). ToString (). Substring (7 );
Context. RewritePath ("~ /Index. aspx? Id = "+ id );
}
}
</Script>