Customizing Site-Wide Behavior

By Microsoft ASP.NET Team|September 28, 2010

This chapter explains how to make settings to your entire website or an entire folder, rather than just a page.

What you'll learn:

  • How to run code that lets you set values (global values or helper settings) for all pages in a site. 
  • How to run code that lets you set values for all pages in a folder. 
  • How to run code before and after a page loads.
  • How to send errors to a central error page.
  • How to add authentication to all pages in a folder.
  • How ASP.NET uses routing to let you use more readable and searchable URLs.

Adding Website Startup Code

Most of the code you write and the settings you make are in individual pages. For example, if a page sends an email message, the page typically contains all the code that's needed in order to initialize the settings for sending email (that is, for the SMTP server) and for sending the email message.

However, in some situations, you might want to run some code before any page on the site runs. This is useful for setting values that can be used anywhere in the site (referred to as global values.) Some helpers require you to provide values like email settings or account keys, for example, and it can be handy to keep these settings in global values.

You can do this by creating a page named _AppStart.cshtml in the root of the site. If this page exists, it runs the first time any page in the site is requested. Therefore, it's a good place to run code to set global values. (Because _AppStart.cshtml has an underscore prefix, ASP.NET won't send the page to a browser even if users request it directly.)

The following diagram shows how the _AppStart.cshtml page works. 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 so, any code in the _AppStart.cshtml page runs, and then the requested page runs.

ch18customizingwebsite-1

Setting Global Values for Your Website

  1. In the root folder of a WebMatrix website, create a file named _AppStart.cshtml. The file must be in the root of the site.
  2. Replace the default markup and code with the following:
    @{
      AppState["customAppName"] = "Application Name";
    }

    This code stores a value in the AppState dictionary, which is automatically available to all pages in the site.

    Note   Be careful when you put code in the _AppStart.cshtml file. If any errors occur in code in the _AppStart.cshtml file, the website won't start.

  3. In the root folder, create a new page named AppName.cshtml.
  4. Replace the default markup and code with the following:
    <!DOCTYPE html>
    <html>
        <head>
            <title>Show Application Name</title>
        </head>
        <body>
            <h1>@AppState["customAppName"]</h1>
        </body>
    </html>

    This code extracts the value from the AppState object that you set in the _AppStart.cshtml page.

  5. Run the AppName.cshtml page in a browser. (Make sure the page is selected in the Files workspace before you run it.) The page displays the global value.

    ch18customizingwebsite-2

Setting Values for Helpers

A good use for the _AppStart.cshtml file is to set values for helpers that you use in your site and that have to be initialized. A perfect example is the ReCaptcha helper, which requires you to specify public and private keys for your reCAPTCHA account. Instead of setting these keys on each page where you want to use the ReCaptcha helper, you can set them once in the _AppStart.cshtml and then they're already set for all the pages in your site. Other values you can set in the _AppStart.cshtml are settings for sending email using an SMTP server, as you saw in Chapter 16 - Adding Security and Membership.

This procedure shows you how to set the ReCaptcha keys globally. (For more information about using the ReCaptcha helper, see Chapter 16 - Adding Security and Membership.)

  1. Add the ASP.NET Web Helpers Library to your website as described in Chapter 1, if you haven't already added it.
  2. If you haven't already, register your website at ReCaptcha.Net (http://recaptcha.net). When you've completed registration, you'll get a public key and a private key.
  3. If you don't already have a _AppStart.cshtml file, in the root folder of a website create a file named _AppStart.cshtml.
  4. Replace the existing code in the _AppStart.cshtml file with the following code:
    @{
      // Add the PublicKey and PrivateKey strings with your public
      // and private keys. Obtain your PublicKey and PrivateKey 
      // at the ReCaptcha.Net (http://recaptcha.net) website.
      ReCaptcha.PublicKey = "";  
      ReCaptcha.PrivateKey = "";  
    }
  5. Set the PublicKey and PrivateKey properties using your own public and private keys.
  6. Save the _AppStart.cshtml file and close it.
  7. In the root folder of a website, create new page named Recaptcha.cshtml.
  8. Replace the default markup and code with the following:
    @{
      var showRecaptcha = true;
      if (IsPost) {  
        if (ReCaptcha.Validate()) {  
            @:Your response passed!
            showRecaptcha = false;
        }
        else{
          @:Your response didn't pass!  
        }  
      }  
    }
    <!DOCTYPE html>
    <html>
        <head>
            <title>Testing Global Recaptcha Keys</title>
        </head>
        <body>
        <form action="" method="post">
        @if(showRecaptcha == true){
            if(ReCaptcha.PrivateKey != ""){
                <p>@ReCaptcha.GetHtml()</p>
                <input type="submit" value="Submit" />
            }
            else {
                <p>You can get your public and private keys at 
                the ReCaptcha.Net website (http://recaptcha.net). 
                Then add the keys to the _AppStart.cshtml file.</p>
            }
        }
        </form>
        </body>
    </html>
  9. Run the Recaptcha.cshtml page in a browser. If the PrivateKey value is valid, the page displays the reCAPTCHA control and a button. If you had not set the keys globally in _AppStart.html, the page would display an error.

    ch18customizingwebsite-3

  10. Enter the words for the test. If you pass the reCAPTCHA test, you see a message to that effect; otherwise you see an error message and the reCAPTCHA control is redisplayed.

Running Code Before and After Files in a Folder

Just like you can use _AppStart.cshtml to write code before pages in the site run, you can write code that runs before (and after) any page in a particular folder run. This is useful for things like setting the same layout page for all the pages in a folder, or for checking that a user is logged in before running a page in the folder.

For pages in particular folders, you can create code in a file named _PageStart.cshtml. The following diagram shows how the _PageStart.cshtml page works. When a request comes in for a page, ASP.NET first checks for a _AppStart.cshtml page and runs that. Then ASP.NET checks whether there's an _PageStart.cshtml page, and if so, runs that. It then runs the requested page.

Inside the _PageStart.cshtml page, you can specify where during processing you want the requested page to run by including a RunPage method. This lets you run code before the requested page runs and then again after it. If you don't include RunPage, all the code in _PageStart.cshtml runs, and then the requested page runs automatically.

ch18customizingwebsite-4

ASP.NET lets you create a hierarchy of _PageStart.cshtml files. You can put an _PageStart.cshtml file in the root of the site and in any subfolder. When a page is requested, the _PageStart.cshtml file at the top-most level (nearest to the site root) runs, followed by the _PageStart.cshtml file in the next subfolder, and so on down the subfolder structure until the request reaches the folder that contains the requested page. After all the applicable _PageStart.cshtml files have run, the requested page runs.

For example, you might have the following combination of _PageStart.cshtml files and default.cshtml file:

@* ~/_PageStart.cshtml *@
@{
  PageData["Color1"] = "Red";
  PageData["Color2"] = "Blue";
}


@* ~/myfolder/_PageStart.cshtml *@
@{
  PageData["Color2"] = "Yellow";
  PageData["Color3"] = "Green";
}


@* ~/myfolder/default.cshtml *@
@PageData["Color1"]
<br/>
@PageData["Color2"]
<br/>
@PageData["Color3"]

When you run default.cshtml, you'll see the following:

Red

Yellow

Green

Running Initialization Code for All Pages in a Folder

A good use for _PageStart.cshtml files is to initialize the same layout page for all files in a single folder.

  1. In the root folder, create a new folder named InitPages.
  2. In the InitPages folder of your website, create a file named _PageStart.cshtml and replace the default markup and code with the following:
    @{
        // Sets the layout page for all pages in the folder.
        Layout = "~/Shared/_Layout1.cshtml";
    
        // Sets a variable available to all pages in the folder.
        PageData["MyBackground"] = "Yellow";
    }
  3. In the root of the website, create a folder named Shared.
  4. In the Shared folder, create a file named _Layout1.cshtml and replace the default markup and code with the following:
    @{
      var backgroundColor = PageData["MyBackground"];
    }
    <!DOCTYPE html>
    <html>
    <head>
      <title>Page Title</title>
      <link type="text/css" href="/Styles/Site.css" rel="stylesheet" />
    </head>
    <body>
      <div id="header">
        Using the _PageStart.cshtml file
      </div>
      <div id="main" style="background-color:@backgroundColor">
        @RenderBody()
      </div>
    <div id="footer">
      &copy; 2010 Contoso. All rights reserved
    </div>
    </body>
    </html>
  5. In the InitPages folder, create a file named Content1.cshtml and replace the default markup with the following:
    <p>This is content page 1.</p>
  6. In the InitPages folder, create another file named Content2.cshtml and replace the default markup with the following:
    <p>This is content page 2.</p>
  7. Run Content1.cshtml in a browser.

    ch18customizingwebsite-5

    When the Content1.cshtml page runs, the _PageStart.cshtml file sets Layout and also sets PageData["MyBackground"] to a color. In Content1.cshtml, the layout and color are applied.

  8. Display Content2.cshtml in a browser.

    The layout is the same, because both pages use the same layout page and color as initialized in _PageStart.cshtml.

Using _PageStart.cshtml to Handle Errors

Another good use for the _PageStart.cshtml file is to create a way to handle programming errors (exceptions) that might occur in any .cshtml page in a folder. This example shows you one way to do this.

  1. In the root folder, create a folder named InitCatch.
  2. In the InitCatch folder of your website, create a file named _PageStart.cshtml and replace the existing markup and code with the following:
    @{ 
        try
        {
            RunPage();
        }
        catch (Exception ex)
        {
            Response.Redirect("~/Error.cshtml?source=" + 
                HttpUtility.UrlEncode(Request.AppRelativeCurrentExecutionFilePath));
        }
    }

    In this code, you try running the requested page explicitly by calling the RunPage method inside a try block. If any programming errors occur in the requested page, the code inside the catch block runs. In this case, the code redirects to a page (Error.cshtml) and passes the name of the file that experienced the error as part of the URL. (You'll create the page shortly.)

  3. In the InitCatch folder of your website, create a file named Exception.cshtml and replace the existing markup and code with the following:
    @{ 
        var db = Database.Open("invalidDatabaseFile");
    }

    For purposes of this example, what you're doing in this page is deliberately creating an error by trying to open a database file that doesn't exist.

  4. In the root folder, create a file named Error.cshtml and replace the existing markup and code with the following:
    <!DOCTYPE html>
    <html>
        <head>
            <title>Error Page</title>
        </head>
        <body>
    <h1>Error report</h1>
    <p>An error occurred while running the following file: @Request["source"]</p>
        </body>
    </html>

    In this page, the expression @Request["source"] gets the value out of the URL and displays it.

  5. In the toolbar, click Save.
  6. Run Exception.cshtml in a browser.

    ch18customizingwebsite-6

    Because an error occurs in Exception.cshtml, the _PageStart.cshtml page redirects to the Error.cshtml file, which displays the message.

    For more information about exceptions, see Chapter 2 - Introduction to ASP.NET Web Programming Using the Razor Syntax.

Using _PageStart.cshtml to Restrict Folder Access

You can also use the _PageStart.cshtml file to restrict access to all the files in a folder.

  1. Create a new website using the Site From Template option.
  2. From the available templates, select Starter Site.
  3. In the root folder, create a folder named AuthenticatedContent.
  4. In the AuthenticatedContent folder, create a file named _PageStart.cshtml and replace the existing markup and code with the following:
    @{
        Response.CacheControl = "no-cache";
    
        if (!WebSecurity.IsAuthenticated) { 
            Response.Redirect("~/Account/Login"); 
        }
    }

    The code starts by preventing all files in the folder from being cached. (This is required for scenarios like public computers, where you don't want one user's cached pages to be available to the next user.) Next, the code determines whether the user has signed in to the site before they can view any of the pages in the folder. If the user is not signed in, the code redirects to the login page.

  5. Create a new page in the AuthenticatedContent folder named Page.cshtml.
  6. Replace the default markup with the following:
    @{  
        Layout = "~/_SiteLayout.cshtml";
        Page.Title = "Authenticated Content";
    }
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
      </head>
      <body>
        Thank you for authenticating! 
      </body>
    </html>
  7. Run Page.cshtml in a browser. The code redirects you to a login page. You must register before logging in. After you've registered and logged in, you can navigate to the page and view its contents.

Creating More Readable and Searchable URLs

The URLs for the pages in your site can have an impact on how well the site works. A URL that's "friendly" can make it easier for people to use the site. It can also help with search-engine optimization (SEO) for the site. ASP.NET websites include the ability to use friendly URLs automatically.

About Routing

ASP.NET lets you create meaningful URLs that describe user actions instead of just pointing to a file on the server. Compare these pairs of URLs for a fictional blog:

http://www.contoso.com/Blog/blog.cshtml?categories=hardware
http://www.contoso.com//Blog/blog.cshtml?startdate=2009-11-01&enddate=2009-11-30

http://www.contoso.com/Blog/categories/hardware/
http://www.contoso.com/Blog/2009/November

In the first pair, a user would have to know that the blog is displayed using the blog.cshtml page, and would then have to construct a query string that gets the right category or date range. The second set of examples is much easier to comprehend and create.

The URLs for the first example also point directly to a specific file (blog.cshtml). If for some reason the blog were moved to another folder on the server, or if the blog were rewritten to use a different page, the links would be wrong. The second set of URLs doesn't point to a specific page, so even if the blog implementation or location changes, the URLs would still be valid.

In ASP.NET, you can create friendlier URLs like those in the above examples because ASP.NET uses routing. Routing creates logical mapping from a URL to a page (or pages) that can fulfill the request. Because the mapping is logical (not physical, to a specific file), routing provides great flexibility in how you define the URLs for your site.

How Routing Works

When ASP.NET processes a request, it reads the URL to determine how to route it. ASP.NET tries to match individual segments of the URL to files on disk, going from left to right. If there's a match, anything remaining in the URL is passed to the page as path information. For example, imagine the following folder structure in a website:

ch18customizingwebsite-7

And imagine that someone makes a request using this URL:

http://www.contoso.com/a/b/c

The search goes like this:

  1. Is there a file with the path and name of /a/b/c.cshtml? If so, run and pass no information. Otherwise ...
  2. Is there a file with the path and name of /a/b.cshtml? If so, use that and pass it the information c to it. Otherwise …
  3. Is there a file with the path and name of /a.cshtml? If so, run that page and pass the information b/c to it.

If the search found no exact matches for .cshtml files in their specified folders, ASP.NET continues looking for these files in turn:

  1. /a/b/c/default.cshtml (no path information).
  2. /a/b/c/index.cshtml (no path information).

Note   To be clear, requests for specific pages (that is, requests that include the .cshtml filename extension) work just like you'd expect. A request like http://www.contoso.com/a/b.cshtml will run the page b.cshtml just fine.

Inside a page, you can get the path information via the page's UrlData property, which is a dictionary. Imagine that you have a file named ViewCustomers.cshtml and your site gets this request:

http://mysite.com/myWebSite/ViewCustomers/1000

As described in the rules above, the request will go to your page. Inside the page, you can use code like the following to get and display the path information (in this case, the value "1000"):

<!DOCTYPE html>
<html>
    <head>
        <title>URLData</title>
    </head>
    <body>
      Customer ID: @UrlData[0].ToString()
    </body>
</html>

Note   Because routing doesn't involve complete file names, there can be ambiguity if you have pages that have the same name but different file-name extensions (for example, MyPage.cshtml and MyPage.html). In order to avoid problems with routing, it's best to make sure that you don't have pages in your site whose names differ only in their extension.

Additional Resources

ASP.NET Web Pages with Razor Syntax Reference

Microsoft ASP.NET Team

By Microsoft ASP.NET Team, ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.