Managing Application and Session State in ASP.NET C#
Implementing Application State Management in ASP.NET
This document analyzes C# code snippets demonstrating how to manage a shared counter across an entire ASP.NET application using the Application
state object. The implementation is split between the default page logic (_default.aspx.cs
) and the global application logic (Global.asax.cs
).
The Default Page Logic (_default.aspx.cs
)
This partial class, located within the AulaIV
namespace, handles user interactions and displays the current application count.
namespace AulaIV
{
public partial class _default : System.Web.UI.Page
{
Page Load Handler: Displaying the Current Count
The Page_Load
method retrieves the current value of the "count"
variable stored in the application state and displays it via lblCount
.
protected void Page_Load(object sender, EventArgs e)
{
this.lblCount.Text = Application.Get("count").ToString();
}
Button Click Handlers: Modifying the Application Count
The following methods handle button clicks to modify the shared counter. Both methods ensure the count is parsed as an integer before modification and then stored back into the Application
state.
Decrementing the Count (btnMin_Click
)
protected void btnMin_Click(object sender, EventArgs e)
{
var count = Int32.Parse(Application.Get("count").ToString());
count -= 1;
this.lblCount.Text = count.ToString();
Application.Set("count", count);
}
Incrementing the Count (btnAdd_Click
)
protected void btnAdd_Click(object sender, EventArgs e)
{
var count = Int32.Parse(Application.Get("count").ToString());
count += 1;
this.lblCount.Text = count.ToString();
Application.Set("count", count);
}
}
}
Global Application Logic (Global.asax
)
This section defines the Global
class, which manages application-wide events, including initialization and session tracking. This is the Part of Global logic.
namespace AulaIV
{
public class Global : System.Web.HttpApplication
{
Application Startup Initialization (Application_Start
)
This event fires when the application first starts. It initializes the shared counter "count"
to zero, ensuring a baseline value.
protected void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
Handling New Sessions (Session_Start
)
When a new user session begins, the application counter is incremented. This mechanism effectively tracks the total number of sessions that have started since the application began running.
protected void Session_Start(object sender, EventArgs e)
{
var count = Int32.Parse(Application.Get("count").ToString());
count += 1;
Application.Set("count", count);
}
Application Request Handling
The code snippet also includes the declaration for handling the beginning of an application request:
protected void Application_BeginRequest(object sender, EventArgs e)
{
// ... implementation details
}
}
}