ASP.NET WP - Global Pages


Advertisements

In this chapter, we will be covering the global pages like _AppStart.cshtml and _PageStart.cshtml, which are not mentioned often, and when they are, it seems to be mentioned as a part of WebMatrix / ASP.Net Web Pages.

_AppStart

The _AppStart.cshtml is executed once when the application first starts. In the root folder of your website, you will see a _AppStart.cshtml file, which is a special file that is used to contain global settings.

AppStart
  • It's an official part of the Web Pages framework which is what the Razor View Engine is based on.

  • The _AppStart in the root folder have a startup code that is executed before the site starts.

  • The _AppStart has an underscore prefix, because of this, the files cannot be browsed directly.

  • If this page exists, ASP.NET runs it the first time before any other page in the site is requested.

Let’s have a look into the AppStart.cshtml file

@{
   App.CacheDuration = 30; 
   // cache content pages for 30 minutes
   // register for main contents which will appear as tabs on the navigation bar
   App.ContentPages = new[] {
      new ContentSource("Blog", "My Blog", "~/Contents/_Blog.cshtml", false),
      new ContentSource("Twitter", "My Tweets", "~/Contents/_Twitter.cshtml", false),
      new ContentSource("Photos", "My Photos", "~/Contents/_Photos.cshtml", false)
   };
}

As you can see that the contents of three pages − blog, twitter and photos will be displayed as tabs in the navigation bar when you run this application as shown in the following screenshot.

Contents Three Pages

_PageStart

Similar to _AppStart, which runs before your site starts, you can also write a code that runs before any other page. For each folder in your web, you can add a file named _PageStart.

  • The _PageStart.cshtml executes every time a page in the same or lower level folder is requested.

  • It is the place for performing per-request processing, such as setting layout pages.

PageStart

Work Flow

When a request comes in for a page, and if this is the first request for any page in the site, ASP.NET first checks whether a _AppStart.cshtml page exists. If an _AppStart.cshtml page exists, then any code in the _AppStart.cshtml page runs first, and then the requested page will run.

Work Flow

When a request comes in for a page, ASP.NET first checks whether there is a _PageStart.cshtml page, and if so, runs that and then runs the requested page.

Advertisements