
You have some variables that are used in your Global.asax file in ASP.NET, and they persist through requests and sessions. You want to store these variables once and use them often. Here we add static fields to our Global.asax file, which means we do not need any code in App_Code to store them.
This C# example code shows how you can use Global.asax in ASP.NET. You can store state variables inside Global.asax.

Here we see how you can add static fields to Global.asax. In dynamic websites, paths are useful to know what requests to rewrite in Application_BeginRequest. We can initialize these paths in Application_Start and then use them through the application's lifecycle. Whenever the application starts up, the path to our page will be stored. This means we can use it quickly to rewrite paths in Application_BeginRequest.
Example Global.asax implementation [C#]
<%@ 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>Next example. Here we look at how you 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.
Example with Application_BeginRequest [C#]
<%@ 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>What the example code does. In this example Global.asax, the path to a file at Folder/Page.aspx is stored in a static variable. Then whenever a request begins, we check PhysicalPath to see if we hit that page.

You can store global variables in ASP.NET in many different places. The best way to do it when you need the variables in other places than Global.asax is a static class. See my material on ASP.NET global variables.
Global Variables ExampleAdding Global.asax file. 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. If you are using a web application project, use the code-behind file.
We saw how you can store statics inside your Global.asax file for performance and clarity. Use static fields or properties in Global.asax for a good place to store application-level variables like paths that will need to be used often. Paths and timestamps are good things to store here.
ASP.NET Tutorials