ASP.NET Web Pages - Global Pages

This chapter is about the global pages AppStart and PageStart.

Before Web Startup: _AppStart

Most server side code are written inside individual web pages. For example, if a web page contains an input form, the web page typically contains server code for reading the data.

However, by creating a page named _AppStart in the root of your site, you can have startup code executed before the site starts. If this page exists, ASP.NET runs it the first time any page in the site is requested.

Typical use for _AppStart is startup code and initialization of global values like counters and global names.

Note 1: _AppStart should have the same file extension as your web pages, like: _AppStart.cshtml. 

Note 2: _AppStart has an underscore prefix. Because of this, the files cannot be browsed directly.

Before Every Page: _PageStart

Just like _AppStart runs before your site starts, you can write code that runs before any page in each folder.

For each folder in your web, you can add a file named _PageStart.

Typical use for _PageStart is setting the layout page for all pages in a folder, or checking that a user is logged in before running a page.

How Does it Work?

The following diagram shows how it works:


When a request comes in, ASP.NET checks whether _AppStart exists. If so, and this is the first request to the site, _AppStart runs.

Then ASP.NET checks whether _PageStart exists. If so, _PageStart runs, before the requested page.

If you include a call to RunPage() inside _PageStart you specify where you want the requested page to run. If not, the _PageStart runs before the requested page.