Customizing Site-Wide Behavior for ASP.NET Web Pages (Razor) Sites
This article explains how to make site-side settings for pages in an ASP.NET Web Pages (Razor) website.
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.
Software versions used in the tutorial
- ASP.NET Web Pages (Razor) 2
- WebMatrix 3
- ASP.NET Web Helpers Library (NuGet package)
This tutorial also works with ASP.NET Web Pages 3 and Visual Studio 2013 (or Visual Studio Express 2013 for Web), except you cannot use the ASP.NET Web Helpers Library.
## Adding Website Startup Code for ASP.NET Web Pages
For much of the code that you write in ASP.NET Web Pages, an individual page can contain all the code that’s required for that page. For example, if a page sends an email message, it’s possible to put all the code for that operation in a single page. This can include the code 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.) For example, some helpers require you to provide values like email settings or account keys. 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.
Setting Global Values for Your Website
- In the root folder of a WebMatrix website, create a file named _AppStart.cshtml. The file must be in the root of the site.
Replace the existing content with the following:
[!code-cshtmlMain]
1: @{
2: AppState["customAppName"] = "Application Name";
3: }
This code stores a value in the
AppState
dictionary, which is automatically available to all pages in the site. Notice that the _AppStart.cshtml file does not have any markup in it. The page will run the code and then redirect to the page that was originally requested.[!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.
- In the root folder, create a new page named AppName.cshtml.
Replace the default markup and code with the following:
[!code-htmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>Show Application Name</title>
5: </head>
6: <body>
7: <h1>@AppState["customAppName"]</h1>
8: </body>
9: </html>
AppState
object that you set in the _AppStart.cshtml page.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.
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. Typical examples are email settings for the WebMail
helper and the private and public keys for the ReCaptcha
helper. In cases like these, you can set the values once in the _AppStart.cshtml and then they’re already set for all the pages in your site.
This procedure shows you how to set WebMail
settings globally. (For more information about using the WebMail
helper, see Adding Email to an ASP.NET Web Pages Site.)
- Add the ASP.NET Web Helpers Library to your website as described in Installing Helpers in an ASP.NET Web Pages Site, if you haven’t already added it.
- If you don’t already have a _AppStart.cshtml file, in the root folder of a website create a file named _AppStart.cshtml.
Add the following
WebMail
settings to the _AppStart.cshtml file:[!code-cshtmlMain]
1: @{
2: // Initialize WebMail helper
3: WebMail.SmtpServer = "your-SMTP-host";
4: WebMail.SmtpPort = 25;
5: WebMail.UserName = "your-user-name-here";
6: WebMail.Password = "your-account-password";
7: WebMail.From = "your-email-address-here";
8: }
Modify the following email related settings in the code:
- Set
your-SMTP-host
to the name of the SMTP server that you have access to. - Set
your-user-name-here
to the user name for your SMTP server account. - Set
your-account-password
to the password for your SMTP server account. - Set
your-email-address-here
to your own email address. This is the email address that the message is sent from. (Some email providers don’t let you specify a differentFrom
address and will use your user name as theFrom
address.)
- Set
- Save the _AppStart.cshtml file and close it.
- In the root folder of a website, create new page named TestEmail.cshtml.
Replace the existing content with the following:
[!code-cshtmlMain]1: @{
2: var message = "";
3: try{
4: if(IsPost){
5: WebMail.Send(
6: to: Request.Form["emailAddress"],
7: subject: Request.Form["emailSubject"],
8: body:Request.Form["emailBody"]
9: );
10: message = "Email sent!";
11: }
12: }
13: catch(Exception ex){
14: message = "Email could not be sent!";
15: }
16: }
17: <!DOCTYPE html>
18: <html lang="en">
19: <head>
20: <meta charset="utf-8" />
21: <title>Test Email</title>
22: </head>
23: <body>
24: <h1>Test Email</h1>
25: <form method="post">
26: <p>
27: <label for="emailAddress">Email address:</label>
28: <input type="text" name="emailAddress" />
29: </p>
30: <p>
31: <label for="emailSubject">Subject:</label>
32: <input type="text" name="emailSubject" />
33: </p>
34: <p>
35: <label for="emailBody">Text to send:</label><br/>
36: <textarea name="emailBody" rows="6"></textarea>
37: </p>
38: <p><input type="submit" value="Send!" /></p>
39: @if(IsPost){
40: <p>@message</p>
41: }
42: </form>
43: </body>
44: </html>
- Run the TestEmail.cshtml page in a browser.
- Fill in the fields to send yourself an email message and then click Send.
Check your email to make sure you’ve gotten the message.
The important part of this example is that the settings that you don’t usually change — like the name of your SMTP server and your email credentials — are set in the _AppStart.cshtml file. That way you don’t need to set them again in each page where you send email. (Although if for some reason you need to change those settings, you can set them individually in a page.) In the page, you only set the values that typically change each time, like the recipient and the body of the email message.
## 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 a _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.
ASP.NET lets you create a hierarchy of _PageStart.cshtml files. You can put a _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:
[!code-cshtmlMain]
1: @* ~/_PageStart.cshtml *@
2: @{
3: PageData["Color1"] = "Red";
4: PageData["Color2"] = "Blue";
5: }
[!code-cshtmlMain]
1: @* ~/myfolder/_PageStart.cshtml *@
2: @{
3: PageData["Color2"] = "Yellow";
4: PageData["Color3"] = "Green";
5: }
[!code-cshtmlMain]
1: @* ~/myfolder/default.cshtml *@
2: @PageData["Color1"]
3: <br/>
4: @PageData["Color2"]
5: <br/>
6: @PageData["Color3"]
When you run /myfolder/default.cshtml, you’ll see the following:
[!code-consoleMain]
1: Red
2:
3: Yellow
4:
5: 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.
- In the root folder, create a new folder named InitPages.
In the InitPages folder of your website, create a file named _PageStart.cshtml and replace the default markup and code with the following:
[!code-cshtmlMain]1: @{
2: // Sets the layout page for all pages in the folder.
3: Layout = "~/Shared/_Layout1.cshtml";
4:
5: // Sets a variable available to all pages in the folder.
6: PageData["MyBackground"] = "Yellow";
7: }
- In the root of the website, create a folder named Shared.
In the Shared folder, create a file named _Layout1.cshtml and replace the default markup and code with the following:
[!code-cshtmlMain]1: @{
2: var backgroundColor = PageData["MyBackground"];
3: }
4: <!DOCTYPE html>
5: <html>
6: <head>
7: <title>Page Title</title>
8: <link type="text/css" href="/Styles/Site.css" rel="stylesheet" />
9: </head>
10: <body>
11: <div id="header">
12: Using the _PageStart.cshtml file
13: </div>
14: <div id="main" style="background-color:@backgroundColor">
15: @RenderBody()
16: </div>
17: <div id="footer">
18: © 2012 Contoso. All rights reserved
19: </div>
20: </body>
21: </html>
In the InitPages folder, create a file named Content1.cshtml and replace the existing content with the following:
[!code-htmlMain]1: <p>This is content page 1.</p>
In the InitPages folder, create another file named Content2.cshtml and replace the default markup with the following:
[!code-htmlMain]1: <p>This is content page 2.</p>
Run Content1.cshtml in a browser.
When the Content1.cshtml page runs, the _PageStart.cshtml file setsLayout
and also setsPageData["MyBackground"]
to a color. In Content1.cshtml, the layout and color are applied.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.
- In the root folder, create a folder named InitCatch.
In the InitCatch folder of your website, create a file named _PageStart.cshtml and replace the existing markup and code with the following:
[!code-cshtmlMain]
1: @{
2: try
3: {
4: RunPage();
5: }
6: catch (Exception ex)
7: {
8: Response.Redirect("~/Error.cshtml?source=" +
9: HttpUtility.UrlEncode(Request.AppRelativeCurrentExecutionFilePath));
10: }
11: }
RunPage
method inside atry
block. If any programming errors occur in the requested page, the code inside thecatch
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.)In the InitCatch folder of your website, create a file named Exception.cshtml and replace the existing markup and code with the following:
[!code-cshtmlMain]
1: @{
2: var db = Database.Open("invalidDatabaseFile");
3: }
In the root folder, create a file named Error.cshtml and replace the existing markup and code with the following:
[!code-htmlMain]
1: <!DOCTYPE html>
2: <html>
3: <head>
4: <title>Error Page</title>
5: </head>
6: <body>
7: <h1>Error report</h1>
8: <p>An error occurred while running the following file: @Request["source"]</p>
9: </body>
10: </html>
@Request["source"]
gets the value out of the URL and displays it.- In the toolbar, click Save.
Run Exception.cshtml in a browser.
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 Introduction to ASP.NET Web Pages 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.
- In WebMatrix, create a new website using the Site From Template option.
- From the available templates, select Starter Site.
- In the root folder, create a folder named AuthenticatedContent.
In the AuthenticatedContent folder, create a file named _PageStart.cshtml and replace the existing markup and code with the following:
[!code-cshtmlMain]
1: @{
2: Response.CacheControl = "no-cache";
3: if (!WebSecurity.IsAuthenticated) {
4: var returnUrl = "~/Account/Login?ReturnUrl=" + Request.Url.LocalPath;
5: Response.Redirect(returnUrl);
6: }
7: }
ReturnUrl
.- Create a new page in the AuthenticatedContent folder named Page.cshtml.
Replace the default markup with the following:
[!code-cshtmlMain]1: @{
2: Layout = "~/_SiteLayout.cshtml";
3: Page.Title = "Authenticated Content";
4: }
5: <!DOCTYPE html>
6: <html>
7: <head>
8: <meta charset="utf-8" />
9: </head>
10: <body>
11: Thank you for authenticating!
12: </body>
13: </html>
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.
Introduction to ASP.NET Web Pages Programming Using the Razor Syntax
|