Home
Map
Global.asax ExampleUse Global.asax in ASP.NET to store static fields and important strings.
ASP.NET
This page was last reviewed on Dec 8, 2023.
Global.asax. 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.
Static fields note. 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.
Example. 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.
So Whenever the application starts up, the path to our page will be stored in a static field.
And This means we can use it quickly to rewrite paths in 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>
Next example. 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.
Here 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.
<%@ 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>
A discussion. 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.
Global Variable
Adding 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.
Also If you are using a web application project (instead of a website project), use the code-behind file.
A summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 8, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.