TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

ASP.NET Global.asax Example

This C# example code uses Global.asax in ASP.NET. You can store state variables inside Global.asax.

Global.asax 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.

Tip: Having static fields in Global.asax means we do not need any code in App_Code to store them.

Example. We add static fields to Global.asax. In dynamic websites, 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's lifecycle.

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_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. 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.

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.

Discussion. 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

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. If you are using a web application project, use the code-behind file.

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. Paths and timestamps are good things to store here.