Usage of Global and URLReWrite in ASP. NET
- 2021-07-01 07:07:21
- OfStack
This article illustrates the usage of Global and URLReWrite in ASP. NET. Share it for your reference. The details are as follows:
Global. asax:
Sometimes called an ASP. NET application file, it provides a way to respond to application-level or module-level events in one central location. You can use this file to implement application security and other tasks.
Key understanding: application_Start;; application_BeginRequest; application_Error;
① application_Start: Application_Start is executed when the website is visited for the first time since the server started up
② Application_Error: Unhandled exception occurred in the program
③ Session_End: Only Session in-process will be called, session_End out-of-process Session will not be called
④ application_BeginRequest: When a request comes, application_BeginRequest will be called. When accessing a static page, application_BeginRequest will not process it, and IIS will directly give the static page file to the browser. The Application_BeginRequest method is called even if a non-existent page is visited.
URLReWrite:
Ugly link: http://localhost/viewPerson.aspx? id=1
Ugly! Virgo can't bear it.
Handsome link: http://localhost/viewPerson-1. aspx
How do you make it like a handsome link?
With application_BeginRequest, no matter what page you visit, except static pages, you turn to the principle of other program processing.
Use regular expressions to match "ugly links". When users visit http://localhost/viewPerson-1. aspx, global. asax will be triggered to call application_BeginRequest method. After regular expressions match successfully, Context. RewritePath ("/ViewPerson. aspx? id= "+ id); Done, make it a "handsome link", it's as simple as that.
Using regular expressions:
protected void Application_BeginRequest(object sender, EventArgs e)
{
Match match = Regex.Match(Context.Request.Path, @"^/ViewPerson\-(\d+)\.aspx$");
if (match.Success)
{
string id = match.Groups[1].Value;// Get ( \d+ ) Is id Value of
Context.RewritePath("/ViewPerson.aspx?id=" + id);
}
}
I hope this article is helpful to everyone's asp. net programming.