Chapter 5: WebPages Global
WebPages Global” (full name in the tutorial flow: ASP.NET Web Pages – Global Pages or Global Files). This lesson covers two special protected files that let you run code globally (site-wide or folder-wide) without putting it in every single page.
These are:
- _AppStart.cshtml → runs once when your entire site first starts (application-level startup)
- _PageStart.cshtml → runs before every page in its folder (folder-level startup)
This is where you put code that should happen “behind the scenes” — things that affect the whole site or a section of it, like setting up global variables, configuring email servers, initializing databases, or forcing a layout/login check everywhere.
Teacher mode: These files are magic because they run automatically — no need to call them from your pages!
1. The Star: _AppStart.cshtml – Site Startup Code
What it does
- Lives in the root folder of your website (not inside any subfolder).
- Runs only once — the very first time any page on your site is requested after the app starts (or restarts, like after IIS recycle or code change).
- Perfect for:
- Setting global variables or constants
- Initializing things like email (WebMail), database connections
- Registering helpers or OAuth providers (Google, Facebook login in old Web Pages)
- Any “do this once at birth” code
Rules & Naming
- Must be named exactly _AppStart.cshtml (C#) or _AppStart.vbhtml (VB)
- Leading underscore (_) → protected file: cannot be browsed directly (typing /_AppStart.cshtml gives 404/forbidden)
- Placed in root (not in Shared or subfolders)
How execution flow works
- Browser requests any page (e.g. /Index.cshtml)
- If this is the first request since app start → ASP.NET looks for _AppStart.cshtml in root
- If found → runs its code before the requested page
- Then normal page runs
- On all future requests → _AppStart skips (doesn’t run again until app restarts)
2. Real Example – Using _AppStart.cshtml
Common real-world uses from old Web Pages sites and W3Schools-style tutorials:
_AppStart.cshtml (in root folder)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
@{ // Global site settings - run once at startup // Set default email server (used later by WebMail helper) WebMail.SmtpServer = "smtp.gmail.com"; WebMail.SmtpPort = 587; WebMail.EnableSsl = true; WebMail.UserName = "yourapp@gmail.com"; WebMail.Password = "your-app-password"; // NEVER hardcode in real life! Use config or secrets WebMail.From = "no-reply@yourwebsite.com"; // Global variables (stored in AppState or just as statics) Application["SiteName"] = "Webliance Learning Hub"; Application["Version"] = "1.2.3"; Application["Counter"] = 0; // can increment later // Example: Initialize simple membership (old WebSecurity) // WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "Email", autoCreateTables: true); // Or set a global layout for ALL pages (if not using _PageStart) // (But usually done per-folder with _PageStart) } |
Now in any page (e.g. Contact.cshtml) you can use these globals without setup:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@{ // No need to set email stuff again! if (IsPost) { WebMail.Send( to: Request["email"], subject: "Contact Form", body: Request["message"] ); <p>Email sent successfully!</p> } } <h2>Contact Us</h2> <p>Site: @Application["SiteName"] (v@Application["Version"])</p> ... |
See? Clean — setup once, use everywhere!
3. The Folder-Level Twin: _PageStart.cshtml
What it does
- Put one in any folder (or subfolder)
- Runs before every page request in that folder and its subfolders
- Great for:
- Forcing a layout on all pages in /Admin/ or /Members/
- Checking login status → redirect if not logged in
- Setting folder-specific variables
- Running code like “log visit” or “set culture”
Important extra power You can call RunPage() inside _PageStart to control when the actual requested page runs.
Example: Force layout + login check in /Members/ folder
Create /Members/_PageStart.cshtml
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
@{ // Run before EVERY page in /Members/ and subfolders Layout = "~/Shared/_MemberLayout.cshtml"; // different layout for members area // Simple auth check (using old WebSecurity) if (!WebSecurity.IsAuthenticated) { Response.Redirect("~/Account/Login?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.AbsolutePath)); return; // stop here } // Or without redirect, just set a message // PageData["UserName"] = WebSecurity.CurrentUserName; } @* If you want the requested page to run AFTER some code, call this: *@ @* RunPage(); *@ // ← usually at the end if you have post-processing @* If you DON'T call RunPage(), the requested page NEVER runs! *@ |
Now every page like /Members/Profile.cshtml or /Members/Dashboard.cshtml automatically:
- Uses the member layout
- Checks if logged in → redirects to login if not
- No need to repeat this code 20 times!
Execution order summary (super important whiteboard drawing):
- Request comes (e.g. /Members/Profile.cshtml)
- _AppStart runs? (only if first request ever)
- _PageStart in root? (if exists)
- _PageStart in /Members/? → runs
- Requested page (/Members/Profile.cshtml) runs
- Layout (if set) wraps everything
4. Quick Comparison Table
| Feature | _AppStart.cshtml | _PageStart.cshtml |
|---|---|---|
| Location | Root only | Any folder (affects that folder + subs) |
| Runs… | Once (first request only) | Before every request in its scope |
| Typical use | Global init (email, DB, counters) | Folder rules (layout, auth, logging) |
| Can call RunPage()? | No (not needed) | Yes — controls when actual page executes |
| Protected? | Yes (_) | Yes (_) |
5. Teacher Advice (2026 perspective)
- In real old Web Pages sites → _AppStart was heavily used for WebMail setup, OAuth (Google/Facebook login init), membership init
- _PageStart → very popular for “admin area protection” or per-section layouts
- Modern equivalent in ASP.NET Core Razor Pages → Program.cs / Startup-like config + _ViewStart.cshtml (for default layout) + middleware for auth
- But the ideas are almost identical — learn them here, you’ll recognize them later!
Questions time? 😊
- Want a full example with counter that increments on every visit (using Application[“Counter”])?
- How to debug if _AppStart doesn’t run?
- Difference from Global.asax in old ASP.NET?
- Or next: WebPages Forms (handling input)?
Just tell me — we’re rolling strong from Hyderabad! Keep going, Webliance! 🚀🇮🇳
