ASP.NET Web Pages - Global Page

This chapter explains the global page AppStart and PageStart.

Before Web Start: _AppStart

Most server-side code is written in independent web pages. For example, if a web page contains an input form, the page usually contains server code to read the data.

However, by creating a page named _AppStart in the site root directory, you can execute startup code before the site starts. If this page exists, ASP.NET will run this page first before any page within the site is requested.

Generally, _AppStart is used to start code and initialize global values, such as counters and global names.

Note 1:The file extension of _AppStart should be the same as the web page, such as _AppStart.cshtml.

Note 2:_AppStart has an underscore prefix. That's why users cannot directly view the file.

Before Each Page: _PageStart

Just like running _AppStart before the site starts, you can run code before any page in a folder.

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

Generally, _PageStart is used to set up layout files for all pages in a folder, or to check user login before running a page.

How Does It Work?

The following illustration shows how it works:

The working principle of AppStart and PageStart on the global page

When a request arrives, ASP.NET checks if _AppStart exists. If it does, and it's the first request to the site, then _AppStart runs.

Then ASP.NET checks if _PageStart exists. If it does, it runs _PageStart before the requested page.

If you reference a call to RunPage() within the _PageStart, you can specify where the requested page runs. Otherwise, _PageStart runs before the requested page.