
Webpages Global in ASP
Sure! Here's an overview of global features and files in ASP.NET Web Pages (WebMatrix), focusing on how to manage application-wide settings, variables, and lifecycle using the Global.asax and application-level state.
ASP.NET Web Pages Global Concepts
1. What is Global.asax?
It’s a special optional file in ASP.NET projects.
Used to handle application-level events like start, end, error handling, session start/end.
Helps initialize app-wide variables, logging, security checks, etc.
2. Creating a Global.asax File in Web Pages
Create a file named Global.asax in your root folder, for example:
<%@ Application Language="C#" %><script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup Application["AppStartTime"] = DateTime.Now; } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session starts Session["VisitorCount"] = 0; } void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); // Log the error or handle it Server.ClearError(); } void Session_End(object sender, EventArgs e) { // Code that runs when session ends } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown }</script>
3. Using Application and Session Variables
Application variables are shared by all users (global across all sessions).
// SetApplication["SiteName"] = "My Web Site";// Getvar siteName = Application["SiteName"];
Session variables are per user session.
// SetSession["UserName"] = "Alice";// Getvar userName = Session["UserName"];
4. Accessing Global Variables in Web Pages
Anywhere in your .cshtml
page:
@{ var siteName = Application["SiteName"]; var userName = Session["UserName"];}<h1>Welcome to @siteName</h1>@if(userName != null) { <p>Hello, @userName!</p>}
5. Why Use Global.asax?
Central place to handle cross-cutting concerns: logging, error handling, caching.
Initialize resources on app start.
Track active users/sessions.
Manage app shutdown cleanups.
6. Alternative: App_Start Folder (for advanced apps)
For larger projects, you can use App_Start
folder with .cs
classes to organize startup code — but Global.asax is simplest for Web Pages.
If you want, I can also show you how to handle errors globally, or how to use HTTP modules in ASP.NET Web Pages! Just ask.