This file is helpful in ASP.NET projects. With it we can store variables that persist through requests and sessions. We store these variables once and use them often.
We add static
fields to our Global.asax file. Having static
fields in Global.asax means we do not need any code in App_Code
to store them.
Paths are useful to know what requests to rewrite in Application_BeginRequest
. We initialize these paths in Application_Start
and use them through the application' life.
static
field.Application_BeginRequest
.<%@ Application Language="C#" %> <script runat="server"> static string _pagePath; void Application_Start(object sender, EventArgs e) { // Code that runs on application startup _pagePath = Server.MapPath("~/Folder/Page.aspx"); } // ... </script>
We can use these static
fields, which will persist through sessions and requests. Here we add the Application_BeginRequest
event handler and use the static
variable.
Page.aspx
is stored in a static
variable.PhysicalPath
to see if we hit that page.<%@ Application Language="C#" %> <script runat="server"> static string _pagePath; void Application_Start(object sender, EventArgs e) { // Code that runs on application startup _pagePath = Server.MapPath("~/Folder/Page.aspx"); } // ... void Application_BeginRequest(object sender, EventArgs e) { string path = Request.PhysicalPath; if (path == _pagePath) { Response.Write("Page viewed"); Response.End(); } } </script>
You can store global variables in ASP.NET in many places. The best way to do it when you need the variables in other places than Global.asax is a static
class
.
Go to Website, Add New Item and find the icon that says Global Application Class. Add this item, and then insert the code into its text.
We stored statics inside a Global.asax file. Use static
members in Global.asax for a good place to store application-level variables like paths that will need to be used often.