100% found this document useful (1 vote)
3K views707 pages

C# .NET Core

Libro de C# .NET Core

Uploaded by

Kevin Moreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
3K views707 pages

C# .NET Core

Libro de C# .NET Core

Uploaded by

Kevin Moreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 707

ASP.

NET 5 Documentation
Release

Microsoft

May 23, 2016


Contents

1 Topics 3
1.1 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.3 Conceptual Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
1.4 Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
1.5 MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
1.6 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
1.7 Working with Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
1.8 Client-Side Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
1.9 Mobile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
1.10 Publishing and Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
1.11 Hosting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
1.12 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
1.13 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
1.14 Migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
1.15 Contribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693

2 Related Resources 701

3 Contribute 703

i
ii
ASP.NET 5 Documentation, Release

Attention: ASP.NET 5 has been renamed to ASP.NET Core 1.0. Read more.

Note: This documentation is a work in progress. Topics marked with a are placeholders that have not been written
yet. You can track the status of these topics through our public documentation issue tracker. Learn how you can
contribute on GitHub.

Contents 1
ASP.NET 5 Documentation, Release

2 Contents
CHAPTER 1

Topics

1.1 Getting Started

1. Install .NET Core


2. Create a new .NET Core project:
mkdir aspnetcoreapp
cd aspnetcoreapp
dotnet new

3. Update the project.json file to add the Kestrel HTTP server package as a dependency:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-rc2-3002702"
},
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final"
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}

4. Restore the packages:


dotnet restore

5. Add a Startup.cs file that defines the request handling logic:


using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;

namespace aspnetcoreapp

3
ASP.NET 5 Documentation, Release

{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(context =>
{
return context.Response.WriteAsync("Hello from ASP.NET Core!");
});
}
}
}

6. Update the code in Program.cs to setup and start the Web host:
using System;
using Microsoft.AspNetCore.Hosting;

namespace aspnetcoreapp
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>()
.Build();

host.Run();
}
}
}

7. Run the app (the dotnet run command will build the app when it’s out of date):
dotnet run

8. Browse to http://localhost:5000:

1.1.1 Next steps

• Building your first ASP.NET Core MVC app with Visual Studio
• Your First ASP.NET Core Application on a Mac Using Visual Studio Code

4 Chapter 1. Topics
ASP.NET 5 Documentation, Release

• Building Your First Web API with ASP.NET Core MVC and Visual Studio
• Fundamentals

1.2 Tutorials

1.2.1 Your First ASP.NET Core Application on a Mac Using Visual Studio Code

By Daniel Roth, Steve Smith and Rick Anderson


This article will show you how to write your first ASP.NET Core application on a Mac.

Sections:
• Setting Up Your Development Environment
• Scaffolding Applications Using Yeoman
• Developing ASP.NET Applications on a Mac With Visual Studio Code
• Running Locally Using Kestrel
• Publishing to Azure
• Additional Resources

Setting Up Your Development Environment

To setup your development machine download and install .NET Core and Visual Studio Code with the C# extension.

Scaffolding Applications Using Yeoman

Follow the instruction in Building Projects with Yeoman to create an ASP.NET Core project.

Developing ASP.NET Applications on a Mac With Visual Studio Code

• Start Visual Studio Code

1.2. Tutorials 5
ASP.NET 5 Documentation, Release

• Tap File > Open and navigate to your Empty ASP.NET Core app

6 Chapter 1. Topics
ASP.NET 5 Documentation, Release

From a Terminal / bash prompt, run dotnet restore to restore the project’s dependencies. Alternately, you can
enter command shift p in Visual Studio Code and then type dot as shown:

You can run commands directly from within Visual Studio Code, including dotnet restore and any tools refer-
enced in the project.json file, as well as custom tasks defined in .vscode/tasks.json.
This empty project template simply displays “Hello World!”. Open Startup.cs in Visual Studio Code to see how this
is configured:

1.2. Tutorials 7
ASP.NET 5 Documentation, Release

If this is your first time using Visual Studio Code (or just Code for short), note that it provides a very streamlined, fast,
clean interface for quickly working with files, while still providing tooling to make writing code extremely productive.
In the left navigation bar, there are four icons, representing four viewlets:
• Explore
• Search
• Git
• Debug
The Explore viewlet allows you to quickly navigate within the folder system, as well as easily see the files you are
currently working with. It displays a badge to indicate whether any files have unsaved changes, and new folders and
files can easily be created (without having to open a separate dialog window). You can easily Save All from a menu
option that appears on mouse over, as well.
The Search viewlet allows you to quickly search within the folder structure, searching filenames as well as contents.
Code will integrate with Git if it is installed on your system. You can easily initialize a new repository, make commits,
and push changes from the Git viewlet.

8 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The Debug viewlet supports interactive debugging of applications.


Finally, Code’s editor has a ton of great features. You’ll notice unused using statements are underlined and can be
removed automatically by using command . when the lightbulb icon appears. Classes and methods also display how
many references there are in the project to them. If you’re coming from Visual Studio, Code includes many of the
same keyboard shortcuts, such as command k c to comment a block of code, and command k u to uncomment.

Running Locally Using Kestrel

The sample is configured to use Kestrel for the web server. You can see it configured in the project.json file, where it
is specified as a dependency.
{
"version": "1.0.0-*",
"compilationOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-rc2-3002702"
},
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",
"Microsoft.AspNetCore.Server.Kestrel.Https": "1.0.0-rc2-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final"
},
"frameworks": {
"netcoreapp1.0": {}
}
}

• Run dotnet run command to launch the app


• Navigate to localhost:5000:

1.2. Tutorials 9
ASP.NET 5 Documentation, Release

• To stop the web server enter Ctrl+C.

Publishing to Azure

Once you’ve developed your application, you can easily use the Git integration built into Visual Studio Code to push
updates to production, hosted on Microsoft Azure.

Initialize Git

Initialize Git in the folder you’re working in. Tap on the Git viewlet and click the Initialize Git repository
button.

10 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Add a commit message and tap enter or tap the checkmark icon to commit the staged files.

1.2. Tutorials 11
ASP.NET 5 Documentation, Release

Git is tracking changes, so if you make an update to a file, the Git viewlet will display the files that have changed since
your last commit.

Initialize Azure Website

You can deploy to Azure Web Apps directly using Git.


• Create a new Web App in Azure. If you don’t have an Azure account, you can create a free trial.
• Configure the Web App in Azure to support continuous deployment using Git.
Record the Git URL for the Web App from the Azure portal:

12 Chapter 1. Topics
ASP.NET 5 Documentation, Release

• In a Terminal window, add a remote named azure with the Git URL you noted previously.
– git remote add azure https://[email protected]:4
• Push to master.
– git push azure master to deploy.

1.2. Tutorials 13
ASP.NET 5 Documentation, Release

• Browse to the newly deployed web app. You should see Hello world!

Additional Resources

• Visual Studio Code


• Building Projects with Yeoman
• Fundamentals

14 Chapter 1. Topics
ASP.NET 5 Documentation, Release

1.2.2 Building Your First Web API with ASP.NET Core MVC and Visual Studio

By Mike Wasson and Rick Anderson


HTTP is not just for serving up web pages. It’s also a powerful platform for building APIs that expose services and
data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so
HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop apps.
In this tutorial, you’ll build a simple web API for managing a list of “to-do” items. You won’t build any UI in this
tutorial.
ASP.NET Core has built-in support for MVC building Web APIs. Unifying the two frameworks makes it simpler to
build apps that include both UI (HTML) and APIs, because now they share the same code base and pipeline.

Note: If you are porting an existing Web API app to ASP.NET Core, see Migrating from ASP.NET Web API

Sections:
• Overview
• Install Fiddler
• Create the project
• Add a model class
• Add a repository class
• Register the repository
• Add a controller
• Getting to-do items
• Use Fiddler to call the API
• Implement the other CRUD operations
• Next steps

Overview

Here is the API that you’ll create:


API Description Request body Response body
GET /api/todo Get all to-do items None Array of to-do items
GET /api/todo/{id} Get an item by ID None To-do item
POST /api/todo Add a new item To-do item To-do item
PUT /api/todo/{id} Update an existing item To-do item None
DELETE /api/todo/{id} Delete an item. None None
The following diagram show the basic design of the app.

1.2. Tutorials 15
ASP.NET 5 Documentation, Release

• The client is whatever consumes the web API (browser, mobile app, and so forth). We aren’t writing a client in
this tutorial.
• A model is an object that represents the data in your application. In this case, the only model is a to-do item.
Models are represented as simple C# classes (POCOs).
• A controller is an object that handles HTTP requests and creates the HTTP response. This app will have a single
controller.
• To keep the tutorial simple the app doesn’t use a database. Instead, it just keeps to-do items in memory. But
we’ll still include a (trivial) data access layer, to illustrate the separation between the web API and the data layer.
For a tutorial that uses a database, see Building your first ASP.NET Core MVC app with Visual Studio.

Install Fiddler

We’re not building a client, we’ll use Fiddler to test the API. Fiddler is a web debugging tool that lets you compose
HTTP requests and view the raw HTTP responses.

Create the project

Start Visual Studio. From the File menu, select New > Project.
Select the ASP.NET Core Web Application project template. Name the project TodoApi and tap OK.

16 Chapter 1. Topics
ASP.NET 5 Documentation, Release

In the New ASP.NET Core Web Application (.NET Core) - TodoApi dialog, select the Web API template. Tap
OK.

1.2. Tutorials 17
ASP.NET 5 Documentation, Release

Add a model class

A model is an object that represents the data in your application. In this case, the only model is a to-do item.
Add a folder named “Models”. In Solution Explorer, right-click the project. Select Add > New Folder. Name the
folder Models.

18 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Note: You can put model classes anywhere in your project, but the Models folder is used by convention.

Next, add a TodoItem class. Right-click the Models folder and select Add > New Item.
In the Add New Item dialog, select the Class template. Name the class TodoItem and click OK.

1.2. Tutorials 19
ASP.NET 5 Documentation, Release

Replace the generated code with:


namespace TodoApi.Models
{
public class TodoItem
{
public string Key { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
}

Add a repository class

A repository is an object that encapsulates the data layer, and contains logic for retrieving data and mapping it to an
entity model. Even though the example app doesn’t use a database, it’s useful to see how you can inject a repository
into your controllers. Create the repository code in the Models folder.
Start by defining a repository interface named ITodoRepository. Use the class template (Add New Item > Class).
using System.Collections.Generic;

namespace TodoApi.Models
{
public interface ITodoRepository
{
void Add(TodoItem item);
IEnumerable<TodoItem> GetAll();
TodoItem Find(string key);
TodoItem Remove(string key);
void Update(TodoItem item);
}
}

20 Chapter 1. Topics
ASP.NET 5 Documentation, Release

This interface defines basic CRUD operations.


Next, add a TodoRepository class that implements ITodoRepository:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace TodoApi.Models
{
public class TodoRepository : ITodoRepository
{
static ConcurrentDictionary<string, TodoItem> _todos =
new ConcurrentDictionary<string, TodoItem>();

public TodoRepository()
{
Add(new TodoItem { Name = "Item1" });
}

public IEnumerable<TodoItem> GetAll()


{
return _todos.Values;
}

public void Add(TodoItem item)


{
item.Key = Guid.NewGuid().ToString();
_todos[item.Key] = item;
}

public TodoItem Find(string key)


{
TodoItem item;
_todos.TryGetValue(key, out item);
return item;
}

public TodoItem Remove(string key)


{
TodoItem item;
_todos.TryGetValue(key, out item);
_todos.TryRemove(key, out item);
return item;
}

public void Update(TodoItem item)


{
_todos[item.Key] = item;
}
}
}

Build the app to verify you don’t have any compiler errors.

1.2. Tutorials 21
ASP.NET 5 Documentation, Release

Register the repository

By defining a repository interface, we can decouple the repository class from the MVC controller that uses it. Instead
of instantiating a TodoRepository inside the controller we will inject an ITodoRepository the built-in support
in ASP.NET Core for dependency injection.
This approach makes it easier to unit test your controllers. Unit tests should inject a mock or stub version of
ITodoRepository. That way, the test narrowly targets the controller logic and not the data access layer.
In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs
file. Add the following using directive:
using TodoApi.Models;

In the ConfigureServices method, add the highlighted code:


public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
// Add our repository type
services.AddSingleton<ITodoRepository, TodoRepository>();
}

Add a controller

In Solution Explorer, right-click the Controllers folder. Select Add > New Item. In the Add New Item dialog, select
the Web API Controller Class template. Name the class TodoController.
Replace the generated code with the following:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;

namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
public TodoController(ITodoRepository todoItems)
{
TodoItems = todoItems;
}
}
}

This defines an empty controller class. In the next sections, we’ll add methods to implement the API.

Getting to-do items

To get to-do items, add the following methods to the TodoController class.
public IEnumerable<TodoItem> GetAll()
{
return TodoItems.GetAll();
}

22 Chapter 1. Topics
ASP.NET 5 Documentation, Release

[HttpGet("{id}", Name = "GetTodo")]


public IActionResult GetById(string id)
{
var item = TodoItems.Find(id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}

These methods implement the two GET methods:


• GET /api/todo
• GET /api/todo/{id}
Here is an example HTTP response for the GetAll method:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Microsoft-IIS/10.0
Date: Thu, 18 Jun 2015 20:51:10 GMT
Content-Length: 82

[{"Key":"4f67d7c5-a2a9-4aae-b030-16003dd829ae","Name":"Item1","IsComplete":false}]

Later in the tutorial I’ll show how you can view the HTTP response using the Fiddler tool.

Routing and URL paths

The [HttpGet] attribute specifies that these are HTTP GET methods. The URL path for each method is constructed as
follows:
• Take the template string in the controller’s route attribute, [Route("api/[controller]")]
• Replace “[Controller]” with the name of the controller, which is the controller class name minus the “Controller”
suffix. For this sample the name of the controller is “todo” (case insensitive). For this sample, the controller
class name is TodoController and the root name is “todo”. ASP.NET MVC Core is not case sensitive.
• If the [HttpGet] attribute also has a template string, append that to the path. This sample doesn’t use a
template string.
For the GetById method, “{id}” is a placeholder variable. In the actual HTTP request, the client will use the ID of
the todo item. At runtime, when MVC invokes GetById, it assigns the value of “{id}” in the URL the method’s
id parameter.

Change the launch URL to “api/todo”

• Right click on the project > Properties


• Select the Debug tab and change the Launch URL to “api/todo”

1.2. Tutorials 23
ASP.NET 5 Documentation, Release

To learn more about request routing see Routing to Controller Actions.

Return values

The GetAll method returns a CLR object. MVC automatically serializes the object to JSON and writes the JSON
into the body of the response message. The response code for this method is 200, assuming there are no unhandled
exceptions. (Unhandled exceptions are translated into 5xx errors.)
In contrast, the GetById method returns the more general IActionResult type, which represents a generic result
type. That’s because GetById has two different return types:
• If no item matches the requested ID, the method returns a 404 error. This is done by returning NotFound.
• Otherwise, the method returns 200 with a JSON response body. This is done by returning an ObjectResult.

Use Fiddler to call the API

This step is optional, but it’s useful to see the raw HTTP responses from the web API. In Visual Studio, press ^F5
to launch the app. Visual Studio launches a browser and navigates to http://localhost:port/api/todo,
where port is a randomly chosen port number. If you’re using Chrome, Edge or Firefox, the todo data will be displayed.
If you’re using IE, IE will prompt to you open or save the todo.json file.
Launch Fiddler. From the File menu, uncheck the Capture Traffic option. This turns off capturing HTTP traffic.

24 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Select the Composer page. In the Parsed tab, type http://localhost:port/api/todo, where port is the
port number. Click Execute to send the request.

The result appears in the sessions list. The response code should be 200. Use the Inspectors tab to view the content
of the response, including the response body.

1.2. Tutorials 25
ASP.NET 5 Documentation, Release

Implement the other CRUD operations

The last step is to add Create, Update, and Delete methods to the controller. These methods are variations on a
theme, so I’ll just show the code and highlight the main differences.

Create

[HttpPost]
public IActionResult Create([FromBody] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
TodoItems.Add(item);
return CreatedAtRoute("GetTodo", new { controller = "Todo", id = item.Key }, item);
}

This is an HTTP POST method, indicated by the [HttpPost] attribute. The [FromBody] attribute tells MVC to get the
value of the to-do item from the body of the HTTP request.
The CreatedAtRoute method returns a 201 response, which is the standard response for an HTTP POST method that

26 Chapter 1. Topics
ASP.NET 5 Documentation, Release

creates a new resource on the server. CreateAtRoute also adds a Location header to the response. The Location
header specifies the URI of the newly created to-do item. See 10.2.2 201 Created.
We can use Fiddler to send a Create request:
1. In the Composer page, select POST from the drop-down.
2. In the request headers text box, add Content-Type: application/json, which is a Content-Type
header with the value application/json. Fiddler automatically adds the Content-Length header.
3. In the request body text box, enter the following: {"Name":"<your to-do item>"}
4. Click Execute.

Here is an example HTTP session. Use the Raw tab to see the session data in this format.
Request:
POST http://localhost:29359/api/todo HTTP/1.1
User-Agent: Fiddler
Host: localhost:29359
Content-Type: application/json
Content-Length: 33

{"Name":"Alphabetize paperclips"}

Response:
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Location: http://localhost:29359/api/Todo/8fa2154d-f862-41f8-a5e5-a9a3faba0233
Server: Microsoft-IIS/10.0
Date: Thu, 18 Jun 2015 20:51:55 GMT
Content-Length: 97

{"Key":"8fa2154d-f862-41f8-a5e5-a9a3faba0233","Name":"Alphabetize paperclips","IsComplete":false}

1.2. Tutorials 27
ASP.NET 5 Documentation, Release

Update

[HttpPut("{id}")]
public IActionResult Update(string id, [FromBody] TodoItem item)
{
if (item == null || item.Key != id)
{
return BadRequest();
}

var todo = TodoItems.Find(id);


if (todo == null)
{
return NotFound();
}

TodoItems.Update(item);
return new NoContentResult();
}

Update is similar to Create, but uses HTTP PUT. The response is 204 (No Content). According to the HTTP spec,
a PUT request requires the client to send the entire updated entity, not just the deltas. To support partial updates, use
HTTP PATCH.

Delete

[HttpDelete("{id}")]
public void Delete(string id)
{
TodoItems.Remove(id);
}

28 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The void return type returns a 204 (No Content) response. That means the client receives a 204 even if the item has
already been deleted, or never existed. There are two ways to think about a request to delete a non-existent resource:
• “Delete” means “delete an existing item”, and the item doesn’t exist, so return 404.
• “Delete” means “ensure the item is not in the collection.” The item is already not in the collection, so return a
204.
Either approach is reasonable. If you return 404, the client will need to handle that case.

Next steps

• To learn about creating a backend for a native mobile app, see Creating Backend Services for Native Mobile
Applications.
• For information about deploying your API, see Publishing and Deployment.
• View or download sample code

1.2.3 Building your first ASP.NET Core MVC app with Visual Studio

Getting started with ASP.NET Core MVC and Visual Studio

By Rick Anderson
This tutorial will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio 2015.

Install Visual Studio and .NET Core

• Install Visual Studio Community 2015. Select the Community download and the default installation. Skip this
step if you have Visual Studio 2015 installed.
– Visual Studio 2015 Home page installer
• Install .NET Core + Visual Studio tooling

1.2. Tutorials 29
ASP.NET 5 Documentation, Release

Create a web app

From the Visual Studio Start page, tap New Project.

Alternatively, you can use the menus to create a new project. Tap File > New > Project.

30 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Complete the New Project dialog:


• In the left pane, tap Web
• In the center pane, tap ASP.NET Core Web Application
• Name the project “MvcMovie” (It’s important to name the project “MvcMovie” so when you copy code, the
namespace will match. )
• Tap OK

1.2. Tutorials 31
ASP.NET 5 Documentation, Release

In the New ASP.NET Core Web Application - MvcMovie dialog, tap Web Application, and then tap OK.

Warning: You must have the Authentication set to Individual User Accounts in this release for the scaffolding
engine to work.

32 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Visual Studio used a default template for the MVC project you just created, so you have a working app right now by
entering a project name and selecting a few options. This is a simple “Hello World!” project, and it’s a good place to
start,
Tap F5 to run the app in debug mode or Ctl-F5 in non-debug mode.

1.2. Tutorials 33
ASP.NET 5 Documentation, Release

• Visual Studio starts IIS Express and runs your app. Notice that the address bar shows localhost:port# and
not something like example.com. That’s because localhost always points to your own local computer,
which in this case is running the app you just created. When Visual Studio creates a web project, a random port
is used for the web server. In the image above, the port number is 1234. When you run the app, you’ll see a
different port number.
• Launching the app with Ctrl+F5 (non-debug mode) allows you to make code changes, save the file, refresh the
browser, and see the code changes. Many developers prefer to use non-debug mode to quickly launch the app
and view changes.
• You can launch the app in debug or non-debug mode from the Debug menu item:

34 Chapter 1. Topics
ASP.NET 5 Documentation, Release

• You can debug the app by tapping the IIS Express button

The default template gives you working Home, Contact, About, Register and Log in links. The browser image above
doesn’t show theses links. Depending on the size of your browser, you might need to click the navigation icon to show
them.

1.2. Tutorials 35
ASP.NET 5 Documentation, Release

In the next part of this tutorial, we’ll learn about MVC and start writing some code.

Adding a controller

By Rick Anderson
The Model-View-Controller (MVC) architectural pattern separates an app into three main components: the Model, the
View, and the Controller. The MVC pattern helps you create apps that are testable and easier to maintain and update
than traditional monolithic apps. MVC-based apps contain:
• Models: Classes that represent the data of the app and that use validation logic to enforce business rules for
that data. Typically, model objects retrieve and store model state in a database. In this tutorial, a Movie model
retrieves movie data from a database, provides it to the view or updates it. Updated data is written to a SQL
Server database.
• Views: Views are the components that display the app’s user interface (UI). Generally, this UI displays the
model data.
• Controllers: Classes that handle browser requests, retrieve model data, and then specify view templates that
return a response to the browser. In an MVC app, the view only displays information; the controller handles and
responds to user input and interaction. For example, the controller handles route data and query-string values,
and passes these values to the model. The model might use these values to query the database.
The MVC pattern helps you create apps that separate the different aspects of the app (input logic, business logic, and
UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic

36 Chapter 1. Topics
ASP.NET 5 Documentation, Release

should be located in the app. The UI logic belongs in the view. Input logic belongs in the controller. Business logic
belongs in the model. This separation helps you manage complexity when you build an app, because it enables you
to work on one aspect of the implementation at a time without impacting the code of another. For example, you can
work on the view code without depending on the business logic code.
We’ll be covering all these concepts in this tutorial series and show you how to use them to build a simple movie app.
The following image shows the Models, Views and Controllers folders in the MVC project.

• In Solution Explorer, right-click Controllers > Add > New Item

1.2. Tutorials 37
ASP.NET 5 Documentation, Release

• In the Add Scaffold dialog


– Tap MVC Controller - Empty
– Tap Add

38 Chapter 1. Topics
ASP.NET 5 Documentation, Release

• Name the controller HelloWorldController


• Tap Add

Replace the contents of Controllers/HelloWorldController.cs with the following:


using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/

public string Index()


{
return "This is my default action...";
}

//
// GET: /HelloWorld/Welcome/

public string Welcome()


{
return "This is the Welcome action method...";
}
}
}

Every public method in a controller is callable as an HTTP endpoint. In the sample above, both methods return a
string. Note the comments preceding each method:
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/

public string Index()


{
return "This is my default action...";
}

//
// GET: /HelloWorld/Welcome/

public string Welcome()


{
return "This is the Welcome action method...";
}

1.2. Tutorials 39
ASP.NET 5 Documentation, Release

The first comment states this is an HTTP GET method that is invoked by appending “/HelloWorld/” to the URL. The
second comment specifies an HTTP GET method that is invoked by appending “/HelloWorld/Welcome/” to the URL.
Later on in the tutorial we’ll use the scaffolding engine to generate HTTP POST methods.
Run the app in non-debug mode (press Ctrl+F5) and append “HelloWorld” to the path in the address bar. (In the image
below, http://localhost:1234/HelloWorld is used, but you’ll have to replace 1234 with the port number of your app.)
The Index method returns a string. You told the system to return some HTML, and it did!

MVC invokes controller classes (and the action methods within them) depending on the incoming URL. The default
URL routing logic used by MVC uses a format like this to determine what code to invoke:
/[Controller]/[ActionName]/[Parameters]
You set the format for routing in the Startup.cs file.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

When you run the app and don’t supply any URL segments, it defaults to the “Home” controller and the “Index”
method specified in the template line highlighted above.
The first URL segment determines the controller class to run. So localhost:xxxx/HelloWorld maps
to the HelloWorldController class. The second part of the URL segment determines the action
method on the class. So localhost:xxxx/HelloWorld/Index would cause the Index method of the
HelloWorldController class to run. Notice that we only had to browse to localhost:xxxx/HelloWorld
and the Index method was called by default. This is because Index is the default method that will be called on
a controller if a method name is not explicitly specified. The third part of the URL segment ( Parameters) is for
route data. We’ll see route data later on in this tutorial.
Browse to http://localhost:xxxx/HelloWorld/Welcome. The Welcome method runs
and returns the string “This is the Welcome action method...”. The default MVC routing is
/[Controller]/[ActionName]/[Parameters]. For this URL, the controller is HelloWorld and
Welcome is the action method. We haven’t used the [Parameters] part of the URL yet.

40 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Let’s modify the example slightly so that you can pass some parameter information from the URL to the controller
(for example, /HelloWorld/Welcome?name=Scott&numtimes=4). Change the Welcome method to in-
clude two parameters as shown below. Note that the code uses the C# optional-parameter feature to indicate that the
numTimes parameter defaults to 1 if no value is passed for that parameter.
public string Welcome(string name, int numTimes = 1)
{
return HtmlEncoder.Default.Encode(
"Hello " + name + ", NumTimes is: " + numTimes);
}

Note: The code above uses HtmlEncoder.Default.Encode to protect the app from malicious input (namely
JavaScript).

Note: In Visual Studio 2015, when you are running without debugging (Ctl+F5), you don’t need to build the app after
changing the code. Just save the file, refresh your browser and you can see the changes.

Run your app and browse to:


http://localhost:xxxx/HelloWorld/Welcome?name=Rick&numtimes=4
(Replace xxxx with your port number.) You can try different values for name and numtimes in the URL. The MVC
model binding system automatically maps the named parameters from the query string in the address bar to parameters
in your method. See Model Binding for more information.

1.2. Tutorials 41
ASP.NET 5 Documentation, Release

In the sample above, the URL segment (Parameters) is not used, the name and numTimes parameters are passed
as query strings. The ? (question mark) in the above URL is a separator, and the query strings follow. The & character
separates query strings.
Replace the Welcome method with the following code:
public string Welcome(string name, int ID = 1)
{
return HtmlEncoder.Default.Encode(
"Hello " + name + ", ID: " + ID);
}

Run the app and enter the following URL: http://localhost:xxx/HelloWorld/Welcome/3?name=Rick

This time the third URL segment matched the route parameter id. The Welcome method contains a parameter id
that matched the URL template in the MapRoute method. The trailing ? (in id?) indicates the id parameter is
optional.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

42 Chapter 1. Topics
ASP.NET 5 Documentation, Release

In these examples the controller has been doing the “VC” portion of MVC - that is, the view and controller work.
The controller is returning HTML directly. Generally you don’t want controllers returning HTML directly, since that
becomes very cumbersome to code and maintain. Instead we’ll typically use a separate Razor view template file to
help generate the HTML response. We’ll do that in the next tutorial.

Adding a view

By Rick Anderson
In this section you’re going to modify the HelloWorldController class to use Razor view template files to
cleanly encapsulate the process of generating HTML responses to a client.
You’ll create a view template file using the Razor view engine. Razor-based view templates have a .cshtml file exten-
sion, and provide an elegant way to create HTML output using C#. Razor minimizes the number of characters and
keystrokes required when writing a view template, and enables a fast, fluid coding workflow.
Currently the Index method returns a string with a message that is hard-coded in the controller class. Change the
Index method to return a View object, as shown in the following code:
public IActionResult Index()
{
return View();
}

The Index method above uses a view template to generate an HTML response to the browser. Controller methods
(also known as action methods), such as the Index method above, generally return an IActionResult (or a class
derived from ActionResult), not primitive types like string.
• Right click on the Views folder, and then Add > New Folder and name the folder HelloWorld.

1.2. Tutorials 43
ASP.NET 5 Documentation, Release

• Right click on the Views/HelloWorld folder, and then Add > New Item.
• In the Add New Item - MvcMovie dialog
– In the search box in the upper-right, enter view
– Tap MVC View Page
– In the Name box, keep the default Index.cshtml
– Tap Add

44 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:
@{
ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>Hello from our View Template!</p>

Navigate to http://localhost:xxxx/HelloWorld. The Index method in the


HelloWorldController didn’t do much work; it simply ran the statement return View();, which
specified that the method should use a view template file to render a response to the browser. Because you didn’t
explicitly specify the name of the view template file to use, MVC defaulted to using the Index.cshtml view file in the
/Views/HelloWorld folder. The image below shows the string “Hello from our View Template!” hard-coded in the
view.

1.2. Tutorials 45
ASP.NET 5 Documentation, Release

If your browser window is small (for example on a mobile device), you might need to toggle (tap) the Bootstrap
navigation button in the upper right to see the to the Home, About, Contact, Register and Log in links.

Changing views and layout pages

Tap on the menu links (MvcMovie, Home, About). Each page shows the same menu layout. The menu layout is
implemented in the Views/Shared/_Layout.cshtml file. Open the Views/Shared/_Layout.cshtml file.
Layout templates allow you to specify the HTML container layout of your site in one place and then apply it across
multiple pages in your site. Find the @RenderBody() line. RenderBody is a placeholder where all the view-
specific pages you create show up, “wrapped” in the layout page. For example, if you select the About link, the
Views/Home/About.cshtml view is rendered inside the RenderBody method.
Change the contents of the title element. Change the anchor text in the layout template to “MVC Movie” and the
controller from Home to Movies as highlighted below:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="utf-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>@ViewData["Title"] - Movie App</title>
7

8 <environment names="Development">
9 <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
10 <link rel="stylesheet" href="~/css/site.css" />
11 </environment>
12 <environment names="Staging,Production">
13 <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.mi

46 Chapter 1. Topics
ASP.NET 5 Documentation, Release

14 asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
15 asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-te
16 <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
17 </environment>
18 </head>
19 <body>
20 <div class="navbar navbar-inverse navbar-fixed-top">
21 <div class="container">
22 <div class="navbar-header">
23 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navb
24 <span class="sr-only">Toggle navigation</span>
25 <span class="icon-bar"></span>
26 <span class="icon-bar"></span>
27 <span class="icon-bar"></span>
28 </button>
29 <a asp-controller="Movies" asp-action="Index" class="navbar-brand">Mvc Movie</a>
30 </div>
31 <div class="navbar-collapse collapse">
32 <ul class="nav navbar-nav">
33 <li><a asp-controller="Home" asp-action="Index">Home</a></li>
34 <li><a asp-controller="Home" asp-action="About">About</a></li>
35 <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
36 </ul>
37 @await Html.PartialAsync("_LoginPartial")
38 </div>
39 </div>
40 </div>
41 <div class="container body-content">
42 @RenderBody()
43 <hr />
44 <footer>
45 <p>&copy; 2016 - MvcMovie</p>
46 </footer>
47 </div>
48

49 <environment names="Development">
50 <script src="~/lib/jquery/dist/jquery.js"></script>
51 <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
52 <script src="~/js/site.js" asp-append-version="true"></script>
53 </environment>
54 <environment names="Staging,Production">
55 <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
56 asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
57 asp-fallback-test="window.jQuery">
58 </script>
59 <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"
60 asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
61 asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
62 </script>
63 <script src="~/js/site.min.js" asp-append-version="true"></script>
64 </environment>
65

66 @RenderSection("scripts", required: false)


67 </body>
68 </html>

Warning: We haven’t implemented the Movies controller yet, so if you click on that link, you’ll get a 404 (Not
found) error.

1.2. Tutorials 47
ASP.NET 5 Documentation, Release

Save your changes and tap the About link. Notice how each page displays the Mvc Movie link. We were able to make
the change once in the layout template and have all pages on the site reflect the new link text and new title.
Examine the Views/_ViewStart.cshtml file:
@{
Layout = "_Layout";
}

The Views/_ViewStart.cshtml file brings in the Views/Shared/_Layout.cshtml file to each view. You can use the
Layout property to set a different layout view, or set it to null so no layout file will be used.
Now, let’s change the title of the Index view.
Open Views/HelloWorld/Index.cshtml. There are two places to make a change:
• The text that appears in the title of the browser
• The secondary header (<h2> element).
You’ll make them slightly different so you can see which bit of code changes which part of the app.
@{
ViewData["Title"] = "Movie List";
}

<h2>My Movie List</h2>

<p>Hello from our View Template!</p>

ViewData["Title"] = "Movie List"; in the code above sets the Title property of the ViewDataDic-
tionary to “Movie List”. The Title property is used in the <title> HTML element in the layout page:
<title>@ViewData["Title"] - Movie App</title>

Save your change and refresh the page. Notice that the browser title, the primary heading, and the secondary headings
have changed. (If you don’t see changes in the browser, you might be viewing cached content. Press Ctrl+F5 in your
browser to force the response from the server to be loaded.) The browser title is created with ViewData["Title"]
we set in the Index.cshtml view template and the additional “- Movie App” added in the layout file.
Also notice how the content in the Index.cshtml view template was merged with the Views/Shared/_Layout.cshtml view
template and a single HTML response was sent to the browser. Layout templates make it really easy to make changes
that apply across all of the pages in your application. To learn more see Layout.

48 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Our little bit of “data” (in this case the “Hello from our View Template!” message) is hard-coded, though. The MVC
application has a “V” (view) and you’ve got a “C” (controller), but no “M” (model) yet. Shortly, we’ll walk through
how create a database and retrieve model data from it.

Passing Data from the Controller to the View

Before we go to a database and talk about models, though, let’s first talk about passing information from the controller
to a view. Controller classes are invoked in response to an incoming URL request. A controller class is where you
write the code that handles the incoming browser requests, retrieves data from a database, and ultimately decides what
type of response to send back to the browser. View templates can then be used from a controller to generate and format
an HTML response to the browser.
Controllers are responsible for providing whatever data or objects are required in order for a view template to render
a response to the browser. A best practice: A view template should never perform business logic or interact with
a database directly. Instead, a view template should work only with the data that’s provided to it by the controller.
Maintaining this “separation of concerns” helps keep your code clean, testable and more maintainable.
Currently, the Welcome method in the HelloWorldController class takes a name and a ID parameter and then
outputs the values directly to the browser. Rather than have the controller render this response as a string, let’s change
the controller to use a view template instead. The view template will generate a dynamic response, which means
that you need to pass appropriate bits of data from the controller to the view in order to generate the response. You
can do this by having the controller put the dynamic data (parameters) that the view template needs in a ViewData
dictionary that the view template can then access.
Return to the HelloWorldController.cs file and change the Welcome method to add a Message and NumTimes value
to the ViewData dictionary. The ViewData dictionary is a dynamic object, which means you can put whatever
you want in to it; the ViewData object has no defined properties until you put something inside it. The MVC model
binding system automatically maps the named parameters (name and numTimes) from the query string in the address
bar to parameters in your method. The complete HelloWorldController.cs file looks like this:
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;

1.2. Tutorials 49
ASP.NET 5 Documentation, Release

namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
public IActionResult Index()
{
return View();
}

public IActionResult Welcome(string name, int numTimes = 1)


{
ViewData["Message"] = "Hello " + name;
ViewData["NumTimes"] = numTimes;

return View();
}
}
}

The ViewData dictionary object contains data that will be passed to the view. Next, you need a Welcome view
template.
• Right click on the Views/HelloWorld folder, and then Add > New Item.
• In the Add New Item - MvcMovie dialog
– In the search box in the upper-right, enter view
– Tap MVC View Page
– In the Name box, enter Welcome.cshtml
– Tap Add
You’ll create a loop in the Welcome.cshtml view template that displays “Hello” NumTimes. Replace the contents of
Views/HelloWorld/Welcome.cshtml with the following:
@{
ViewData["Title"] = "About";
}

<h2>Welcome</h2>

<ul>
@for (int i = 0; i < (int)ViewData["NumTimes"]; i++)
{
<li>@ViewData["Message"]</li>
}
</ul>

Save your changes and browse to the following URL:


http://localhost:xxxx/HelloWorld/Welcome?name=Rick&numtimes=4
Data is taken from the URL and passed to the controller using the model binder. The controller packages the data into
a ViewData dictionary and passes that object to the view. The view then renders the data as HTML to the browser.

50 Chapter 1. Topics
ASP.NET 5 Documentation, Release

In the sample above, we used the ViewData dictionary to pass data from the controller to a view. Later in the
tutorial, we will use a view model to pass data from a controller to a view. The view model approach to passing data is
generally much preferred over the ViewData dictionary approach. See Dynamic V Strongly Typed Views for more
information.
Well, that was a kind of an “M” for model, but not the database kind. Let’s take what we’ve learned and create a
database of movies.

Adding a model

By Rick Anderson
In this section you’ll add some classes for managing movies in a database. These classes will be the “Model” part of
the MVC app.
You’ll use a .NET Framework data-access technology known as the Entity Framework Core to define and work with
these data model classes. Entity Framework Core (often referred to as EF Core) features a development paradigm
called Code First. You write the code first, and the database tables are created from this code. Code First allows you
to create data model objects by writing simple classes. (These are also known as POCO classes, from “plain-old CLR
objects.”) The database is created from your classes. If you are required to create the database first, you can still follow
this tutorial to learn about MVC and EF app development.

Adding data model classes

In Solution Explorer, right click the Models folder > Add > Class. Name the class Movie and add the following
properties:
using System;

1.2. Tutorials 51
ASP.NET 5 Documentation, Release

namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}

In addition to the properties you’d expect to model a movie, the ID field is required by the DB for the primary key.
Build the project. If you don’t build the app, you’ll get an error in the next section. We’ve finally added a Model to
our MVC app.

Scaffolding a controller

In Solution Explorer, right-click the Controllers folder > Add > Controller.

52 Chapter 1. Topics
ASP.NET 5 Documentation, Release

In the Add Scaffold dialog, tap MVC Controller with views, using Entity Framework > Add.

1.2. Tutorials 53
ASP.NET 5 Documentation, Release

Complete the Add Controller dialog


• Model class: Movie(MvcMovie.Models)
• Data context class: ApplicationDbContext(MvcMovie.Models)
• Views:: Keep the default of each option checked
• Controller name: Keep the default MoviesController
• Tap Add

54 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The Visual Studio scaffolding engine creates the following:


• A movies controller (Controllers/MoviesController.cs)
• Create, Delete, Details, Edit and Index Razor view files (Views/Movies)
Visual Studio automatically created the CRUD (create, read, update, and delete) action methods and views for you (the
automatic creation of CRUD action methods and views is known as scaffolding). You’ll soon have a fully functional
web application that lets you create, list, edit, and delete movie entries.
Run the app and click on the Mvc Movie link. You’ll get the following error:

That’s a great error message, we’ll follow those instructions to get the database ready for our Movie app.

Use data migrations to create the database

• Open a command prompt in the project directory (MvcMovie/src/MvcMovie). Follow these instructions for a
quick way to open a folder in the project directory.
– Open a file in the root of the project (for this example, use Startup.cs.)
– Right click on Startup.cs > Open Containing Folder.

1.2. Tutorials 55
ASP.NET 5 Documentation, Release

– Shift + right click a folder > Open command window here

– Run cd .. to move back up to the project directory


• Run the following commands in the command prompt:
dotnet ef migrations add Initial
dotnet ef database update

• dotnet (.NET Core) is a cross-platform implementation of .NET. You can read about it here.
• dotnet ef migrations add Initial Runs the Entity Framework .NET Core CLI migrations com-
mand and creates the initial migration. The parameter “Initial” is arbitrary, but customary for the first (initial)
database migration. This operation creates the Data/Migrations/2016<date-time>_Initial.cs file containing the
migration commands to add (or drop) the Movie table to the database.

56 Chapter 1. Topics
ASP.NET 5 Documentation, Release

• dotnet ef database update Updates the database with the migration we just created.

Test the app

• Run the app and tap the Mvc Movie link


• Tap the Create New link and create a movie

1.2. Tutorials 57
ASP.NET 5 Documentation, Release

Note: You may not be able to enter decimal points or commas in the Price field. To support jQuery validation for
non-English locales that use a comma (”,”) for a decimal point, and non US-English date formats, you must take steps
to globalize your app. See Additional resources for more information. For now, just enter whole numbers like 10.

Tapping Create causes the form to be posted to the server, where the movie information is saved in a database. You
are then redirected to the /Movies URL, where you can see the newly created movie in the listing.

Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional.

Examining the Generated Code

Open the Controllers/MoviesController.cs file and examine the generated Index method. A portion of the movie
controller with the Index method is shown below:
public class MoviesController : Controller
{
private readonly ApplicationDbContext _context;

public MoviesController(ApplicationDbContext context)


{
_context = context;
}

public async Task<IActionResult> Index()


{

58 Chapter 1. Topics
ASP.NET 5 Documentation, Release

return View(await _context.Movie.ToListAsync());


}

The constructor uses Dependency Injection to inject the database context into the controller. The database context is
used in each of the CRUD methods in the controller.
A request to the Movies controller returns all the entries in the Movies table and then passes the data to the Index
view.

Strongly typed models and the @model keyword Earlier in this tutorial, you saw how a controller can pass data
or objects to a view template using the ViewData dictionary. The ViewData dictionary is a dynamic object that
provides a convenient late-bound way to pass information to a view.
MVC also provides the ability to pass strongly typed objects to a view template. This strongly typed approach enables
better compile-time checking of your code and richer IntelliSense in Visual Studio (VS). The scaffolding mechanism
in VS used this approach (that is, passing a strongly typed model) with the MoviesController class and view
templates when it created the methods and views.
Examine the generated Details method in the Controllers/MoviesController.cs file:
// GET: Movies/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);


if (movie == null)
{
return NotFound();
}

return View(movie);
}

The id parameter is generally passed as route data, for example http://localhost:1234/movies/details/1


sets:
• The controller to the movies controller (the first URL segment)
• The action to details (the second URL segment)
• The id to 1 (the last URL segment)
You could also pass in the id with a query string as follows:
http://localhost:1234/movies/details?id=1
If a Movie is found, an instance of the Movie model is passed to the Details view:
return View(movie);

Examine the contents of the Views/Movies/Details.cshtml file:


@model MvcMovie.Models.Movie

@{
ViewData["Title"] = "Details";
}

1.2. Tutorials 59
ASP.NET 5 Documentation, Release

<h2>Details</h2>

<div>
<h4>Movie</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Genre)
</dt>
<dd>
@Html.DisplayFor(model => model.Genre)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Price)
</dt>
<dd>
@Html.DisplayFor(model => model.Price)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ReleaseDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ReleaseDate)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model.ID">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>

By including a @model statement at the top of the view template file, you can specify the type of object that the
view expects. When you created the movie controller, Visual Studio automatically included the following @model
statement at the top of the Details.cshtml file:
@model MvcMovie.Models.Movie

This @model directive allows you to access the movie that the controller passed to the view by using a Model
object that’s strongly typed. For example, in the Details.cshtml template, the code passes each movie field to the
DisplayNameFor and DisplayFor HTML Helpers with the strongly typed Model object. The Create and
Edit methods and view templates also pass a Movie model object.
Examine the Index.cshtml view template and the Index method in the Movies controller. Notice how the code creates
a List object when it calls the View method. The code passes this Movies list from the Index action method to
the view:
public async Task<IActionResult> Index()
{
return View(await _context.Movie.ToListAsync());
}

When you created the movies controller, Visual Studio automatically included the following @model statement at the

60 Chapter 1. Topics
ASP.NET 5 Documentation, Release

top of the Index.cshtml file:


@model IEnumerable<MvcMovie.Models.Movie>

The @model directive allows you to access the list of movies that the controller passed to the view by using a Model
object that’s strongly typed. For example, in the Index.cshtml template, the code loops through the movies with a
foreach statement over the strongly typed Model object:
@model IEnumerable<MvcMovie.Models.Movie>

@{
ViewData["Title"] = "Index";
}

<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>

<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}

1.2. Tutorials 61
ASP.NET 5 Documentation, Release

</tbody>
</table>

Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item in the loop is typed
as Movie. Among other benefits, this means that you get compile-time checking of the code and full IntelliSense
support in the code editor:

You now have a database and pages to display, edit, update and delete data. In the next tutorial, we’ll work with the
database.

Additional resources

• Tag Helpers
• Globalization and localization

Working with SQL Server LocalDB

By Rick Anderson
The ApplicationDbContext class handles the task of connecting to the database and mapping Movie ob-
jects to database records. The database context is registered with the Dependency Injection container in the
ConfigureServices method in the Startup.cs file:

62 Chapter 1. Topics
ASP.NET 5 Documentation, Release

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

The ASP.NET Core Configuration system reads the ConnectionString. For local development, it gets the con-
nection string from the appsettings.json file:
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-MvcMovie-7db2893b-375e-48bd-
},
"Logging": {
"IncludeScopes": false,

When you deploy the app to a test or production server, you can use an environment variable or another approach to
set the connection string to a real SQL Server. See Configuration .

SQL Server Express LocalDB

LocalDB is a lightweight version of the SQL Server Express Database Engine that is targeted for program develop-
ment. LocalDB starts on demand and runs in user mode, so there is no complex configuration. By default, LocalDB
database creates “*.mdf” files in the C:/Users/<user> directory.
• From the View menu, open SQL Server Object Explorer (SSOX).

• Right click on the Movie table > View Designer

1.2. Tutorials 63
ASP.NET 5 Documentation, Release

64 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Note the key icon next to ID. By default, EF will make a property named ID the primary key.
• Right click on the Movie table > View Data

1.2. Tutorials 65
ASP.NET 5 Documentation, Release

66 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Seed the database

Create a new class named SeedData in the Models folder. Replace the generated code with the following:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;

namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
if (context.Movie.Any())
{
return; // DB has been seeded
}

context.Movie.AddRange(
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Price = 7.99M
},

1.2. Tutorials 67
ASP.NET 5 Documentation, Release

new Movie
{
Title = "Ghostbusters ",
ReleaseDate = DateTime.Parse("1984-3-13"),
Genre = "Comedy",
Price = 8.99M
},

new Movie
{
Title = "Ghostbusters 2",
ReleaseDate = DateTime.Parse("1986-2-23"),
Genre = "Comedy",
Price = 9.99M
},

new Movie
{
Title = "Rio Bravo",
ReleaseDate = DateTime.Parse("1959-4-15"),
Genre = "Western",
Price = 3.99M
}
);
context.SaveChanges();
}
}
}
}

Notice if there are any movies in the DB, the seed initializer returns.
if (context.Movie.Any())
{
return; // DB has been seeded
}

Add the seed initializer to the end of the Configure method in the Startup.cs file:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

SeedData.Initialize(app.ApplicationServices);
}

Test the app


• Delete all the records in the DB. You can do this with the delete links in the browser or from SSOX.
• Force the app to initialize (call the methods in the Startup class) so the seed method runs. To force initializa-
tion, IIS Express must be stopped and restarted. You can do this with any of the following approaches:

Note: If the database doesn’t initialize, put a break point on the line if (context.Movie.Any()) and start
debugging.

68 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The app shows the seeded data.

1.2. Tutorials 69
ASP.NET 5 Documentation, Release

Controller methods and views

By Rick Anderson
We have a good start to the movie app, but the presentation is not ideal. We don’t want to see the time on the release
date and ReleaseDate should be two words.

70 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Open the Models/Movie.cs file and add the highlighted lines shown below:
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }

[Display(Name = "Release Date")]


[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}

• Right click on a red squiggly line > Quick Actions.

1.2. Tutorials 71
ASP.NET 5 Documentation, Release

• Tap using System.ComponentModel.DataAnnotations;

Visual studio adds using System.ComponentModel.DataAnnotations;.


Let’s remove the using statements that are not needed. They show up by default in a light grey font. Right click
anywhere in the Movie.cs file > Organize Usings > Remove Unnecessary Usings.

72 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The updated code:


using System;
using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }

1.2. Tutorials 73
ASP.NET 5 Documentation, Release

public string Title { get; set; }

[Display(Name = "Release Date")]


[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}

We’ll cover DataAnnotations in the next tutorial. The Display attribute specifies what to display for the name of a field
(in this case “Release Date” instead of “ReleaseDate”). The DataType attribute specifies the type of the data, in this
case it’s a date, so the time information stored in the field is not displayed.
Browse to the Movies controller and hold the mouse pointer over an Edit link to see the target URL.

The Edit, Details, and Delete links are generated by the MVC Core Anchor Tag Helper in the
Views/Movies/Index.cshtml file.
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>

74 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Tag Helpers enable server-side code to participate in creating and rendering HTML elements in Razor files. In the
code above, the AnchorTagHelper dynamically generates the HTML href attribute value from the controller action
method and route id. You use View Source from your favorite browser or use the F12 tools to examine the generated
markup. The F12 tools are shown below.

Recall the format for routing set in the Startup.cs file.


app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

ASP.NET Core translates http://localhost:1234/Movies/Edit/4 into a request to the Edit action


method of the Movies controller with the parameter ID of 4. (Controller methods are also known as action methods.)
Tag Helpers are one of the most popular new features in ASP.NET Core. See Additional resources for more informa-
tion.
Open the Movies controller and examine the two Edit action methods:

1.2. Tutorials 75
ASP.NET 5 Documentation, Release

// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);


if (movie == null)
{
return NotFound();
}
return View(movie);
}

// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, fo
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
if (id != movie.ID)

76 Chapter 1. Topics
ASP.NET 5 Documentation, Release

{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction("Index");
}
return View(movie);
}

The [Bind] attribute is one way to protect against over-posting. You should only include properties in the [Bind]
attribute that you want to change. See Protect your controller from over-posting for more information. ViewModels
provide an alternative approach to prevent over-posting.
Notice the second Edit action method is preceded by the [HttpPost] attribute.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
if (id != movie.ID)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return NotFound();
}
else
{
throw;
}

1.2. Tutorials 77
ASP.NET 5 Documentation, Release

}
return RedirectToAction("Index");
}
return View(movie);
}

The [HttpPost] attribute specifies that this Edit method can be invoked only for POST requests. You could apply the
[HttpGet] attribute to the first edit method, but that’s not necessary because [HttpGet] is the default.
The [ValidateAntiForgeryToken] attribute is used to prevent forgery of a request and is paired up with an anti-forgery
token generated in the edit view file (Views/Movies/Edit.cshtml). The edit view file generates the anti-forgery token in
the Form Tag Helper.
<form asp-action="Edit">

The Form Tag Helper generates a hidden anti-forgery token that must match the
[ValidateAntiForgeryToken] generated anti-forgery token in the Edit method of the Movies controller.
For more information, see Anti-Request Forgery.
The HttpGet Edit method takes the movie ID parameter, looks up the movie using the Entity Framework
SingleOrDefaultAsync method, and returns the selected movie to the Edit view. If a movie cannot be found,
NotFound (HTTP 404) is returned.
// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}

var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);


if (movie == null)
{
return NotFound();
}
return View(movie);
}

When the scaffolding system created the Edit view, it examined the Movie class and created code to render <label>
and <input> elements for each property of the class. The following example shows the Edit view that was generated
by the visual studio scaffolding system:
@model MvcMovie.Models.Movie

@{
ViewData["Title"] = "Edit";
}

<h2>Edit</h2>

<form asp-action="Edit">
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="ID" />
<div class="form-group">
<label asp-for="Genre" class="col-md-2 control-label"></label>

78 Chapter 1. Topics
ASP.NET 5 Documentation, Release

<div class="col-md-10">
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Price" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="Title" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
</form>

<div>
<a asp-action="Index">Back to List</a>
</div>

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Notice how the view template has a @model MvcMovie.Models.Movie statement at the top of the file — this
specifies that the view expects the model for the view template to be of type Movie.
The scaffolded code uses several Tag Helper methods to streamline the HTML markup. The - Label Tag Helper
displays the name of the field (“Title”, “ReleaseDate”, “Genre”, or “Price”). The Input Tag Helper renders an HTML
<input> element. The Validation Tag Helper displays any validation messages associated with that property.
Run the application and navigate to the /Movies URL. Click an Edit link. In the browser, view the source for the
page. The generated HTML for the <form> element is shown below.
<form action="/Movies/Edit/7" method="post">
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
<div class="text-danger" />
<input type="hidden" data-val="true" data-val-required="The ID field is required." id="ID" na
<div class="form-group">

1.2. Tutorials 79
ASP.NET 5 Documentation, Release

<label class="control-label col-md-2" for="Genre" />


<div class="col-md-10">
<input class="form-control" type="text" id="Genre" name="Genre" value="Western" />
<span class="text-danger field-validation-valid" data-valmsg-for="Genre" data-valmsg-
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2" for="Price" />
<div class="col-md-10">
<input class="form-control" type="text" data-val="true" data-val-number="The field Pr
<span class="text-danger field-validation-valid" data-valmsg-for="Price" data-valmsg-
</div>
</div>
<!-- Markup removed for brevity -->
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8Inyxgp63fRFqUePGvuI5jGZsloJu1L
</form>

The <input> elements are in an HTML <form> element whose action attribute is set to post to the
/Movies/Edit/id URL. The form data will be posted to the server when the Save button is clicked. The last line
before the closing </form> element shows the hidden XSRF token generated by the Form Tag Helper.

Processing the POST Request

The following listing shows the [HttpPost] version of the Edit action method.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Genre,Price,ReleaseDate,Title")] Movie movie)
{
if (id != movie.ID)
{
return NotFound();
}

if (ModelState.IsValid)
{
try
{
_context.Update(movie);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!MovieExists(movie.ID))
{
return NotFound();
}
else
{
throw;
}

80 Chapter 1. Topics
ASP.NET 5 Documentation, Release

}
return RedirectToAction("Index");
}
return View(movie);
}

The [ValidateAntiForgeryToken] attribute validates the hidden XSRF token generated by the anti-forgery
token generator in the Form Tag Helper
The model binding system takes the posted form values and creates a Movie object that’s passed as the movie
parameter. The ModelState.IsValid method verifies that the data submitted in the form can be used to modify
(edit or update) a Movie object. If the data is valid it’s saved. The updated (edited) movie data is saved to the database
by calling the SaveChangesAsync method of database contentex. After saving the data, the code redirects the user
to the Index action method of the MoviesController class, which displays the movie collection, including the
changes just made.
Before the form is posted to the server, client side validation checks any validation rules on the fields. If there are
any validation errors, an error message is displayed and the form is not posted. If JavaScript is disabled, you won’t
have client side validation but the server will detect the posted values that are not valid, and the form values will
be redisplayed with error messages. Later in the tutorial we examine Model Validation validation in more detail.
The Validation Tag Helper in the Views/Book/Edit.cshtml view template takes care of displaying appropriate error
messages.

1.2. Tutorials 81
ASP.NET 5 Documentation, Release

All the HttpGet methods in the movie controller follow a similar pattern. They get a movie object (or list of objects,
in the case of Index), and pass the object (model) to the view. The Create method passes an empty movie object
to the Create view. All the methods that create, edit, delete, or otherwise modify data do so in the [HttpPost]
overload of the method. Modifying data in an HTTP GET method is a security risk, as in ASP.NET MVC Tip #46
– Don’t use Delete Links because they create Security Holes. Modifying data in a HTTP GET method also violates
HTTP best practices and the architectural REST pattern, which specifies that GET requests should not change the state

82 Chapter 1. Topics
ASP.NET 5 Documentation, Release

of your application. In other words, performing a GET operation should be a safe operation that has no side effects
and doesn’t modify your persisted data.

Additional resources

• Globalization and localization


• Introduction to Tag Helpers
• Authoring Tag Helpers
• Anti-Request Forgery
• Protect your controller from over-posting
• ViewModels
• Form Tag Helper
• Input Tag Helper
• Label Tag Helper
• Select Tag Helper
• Validation Tag Helper

Adding Search

By Rick Anderson
In this section you’ll add search capability to the Index action method that lets you search movies by genre or name.
Update the Index action method to enable search:
public async Task<IActionResult> Index(string searchString)
{
var movies = from m in _context.Movie
select m;

if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}

return View(await movies.ToListAsync());


}

The first line of the Index action method creates a LINQ query to select the movies:
var movies = from m in _context.Movie
select m;

The query is only defined at this point, it has not been run against the database.
If the searchString parameter contains a string, the movies query is modified to filter on the value of the search
string, using the following code:
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}

1.2. Tutorials 83
ASP.NET 5 Documentation, Release

The s => s.Title.Contains() code above is a Lambda Expression. Lambdas are used in method-based LINQ
queries as arguments to standard query operator methods such as the Where method or Contains used in the code
above. LINQ queries are not executed when they are defined or when they are modified by calling a method such
as Where, Contains or OrderBy. Instead, query execution is deferred, which means that the evaluation of an
expression is delayed until its realized value is actually iterated over or the ToListAsync method is called. For
more information about deferred query execution, see Query Execution.

Note: The Contains method is run on the database, not the c# code above. On the database, Contains maps to SQL
LIKE, which is case insensitive.

Navigate to /Movies/Index. Append a query string such as ?searchString=ghost to the URL. The filtered
movies are displayed.

If you change the signature of the Index method to have a parameter named id, the id parameter will match the
optional {id} placeholder for the default routes set in Startup.cs.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

You can quickly rename the searchString parameter to id with the rename command. Right click on
searchString > Rename.

84 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The rename targets are highlighted.

1.2. Tutorials 85
ASP.NET 5 Documentation, Release

Change the parameter to id and all occurrences of searchString change to id.

The previous Index method:


public async Task<IActionResult> Index(string searchString)
{
var movies = from m in _context.Movie
select m;

if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}

return View(await movies.ToListAsync());


}

The updated Index method:


public async Task<IActionResult> Index(string id)
{
var movies = from m in _context.Movie
select m;

if (!String.IsNullOrEmpty(id))
{
movies = movies.Where(s => s.Title.Contains(id));
}

return View(await movies.ToListAsync());


}

86 Chapter 1. Topics
ASP.NET 5 Documentation, Release

You can now pass the search title as route data (a URL segment) instead of as a query string value.

However, you can’t expect users to modify the URL every time they want to search for a movie. So now you’ll add UI
to help them filter movies. If you changed the signature of the Index method to test how to pass the route-bound ID
parameter, change it back so that it takes a parameter named searchString:
public async Task<IActionResult> Index(string searchString)
{
var movies = from m in _context.Movie
select m;

if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}

return View(await movies.ToListAsync());


}

@model IEnumerable<MvcMovie.Models.Movie>

@{
ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
<a asp-action="Create">Create New</a>

1.2. Tutorials 87
ASP.NET 5 Documentation, Release

</p>

<form asp-controller="Movies" asp-action="Index">


<p>
Title: <input type="text" name="SearchString">
<input type="submit" value="Filter" />
</p>
</form>

<table class="table">
<thead>

The HTML <form> tag uses the Form Tag Helper, so when you submit the form, the filter string is posted to the
Index action of the movies controller. Save your changes and then test the filter.

There’s no [HttpPost] overload of the Index method as you might expect. You don’t need it, because the method
isn’t changing the state of the app, just filtering data.
You could add the following [HttpPost] Index method.
[HttpPost]
public string Index(string searchString, bool notUsed)
{
return "From [HttpPost]Index: filter on " + searchString;
}

88 Chapter 1. Topics
ASP.NET 5 Documentation, Release

The notUsed parameter is used to create an overload for the Index method. We’ll talk about that later in the tutorial.
If you add this method, the action invoker would match the [HttpPost] Index method, and the [HttpPost]
Index method would run as shown in the image below.

However, even if you add this [HttpPost] version of the Index method, there’s a limitation in how this has all
been implemented. Imagine that you want to bookmark a particular search or you want to send a link to friends that
they can click in order to see the same filtered list of movies. Notice that the URL for the HTTP POST request is the
same as the URL for the GET request (localhost:xxxxx/Movies/Index) – there’s no search information in the URL.
The search string information is sent to the server as a form field value. You can verify that with the F12 Developer
tools or the excellent Fiddler tool. Start the F12 tool:
Tap the http://localhost:xxx/Movies HTTP POST 200 line and then tap Body > Request Body.

1.2. Tutorials 89
ASP.NET 5 Documentation, Release

You can see the search parameter and XSRF token in the request body. Note, as mentioned in the previous tutorial, the
Form Tag Helper generates an XSRF anti-forgery token. We’re not modifying data, so we don’t need to validate the
token in the controller method.
Because the search parameter is in the request body and not the URL, you can’t capture that search information to
bookmark or share with others. We’ll fix this by specifying the request should be HTTP GET. Notice how intelliSense
helps us update the markup.

90 Chapter 1. Topics
ASP.NET 5 Documentation, Release

Notice the distinctive font in the <form> tag. That distinctive font indicates the tag is supported by Tag Helpers.

Now when you submit a search, the URL contains the search query string. Searching will also go to the HttpGet
Index action method, even if you have a HttpPost Index method.

Adding Search by Genre

Add the following MovieGenreViewModel class to the Models folder:


using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;

namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
public List<Movie> movies;

1.2. Tutorials 91
ASP.NET 5 Documentation, Release

public SelectList genres;


public string movieGenre { get; set; }
}
}

The move-genre view model will contain:


• a list of movies
• a SelectList containing the list of genres. This will allow the user to select a genre from the list.
• movieGenre, which contains the selected genre
Replace the Index method with the following code:
public async Task<IActionResult> Index(string movieGenre, string searchString)
{
IQueryable<string> genreQuery = from m in _context.Movie
orderby m.Genre
select m.Genre;

var movies = from m in _context.Movie


select m;

if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}

if (!String.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}

var movieGenreVM = new MovieGenreViewModel();


movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());
movieGenreVM.movies = await movies.ToListAsync();

return View(movieGenreVM);
}

The following code is a LINQ query that retrieves all the genres from the database.
IQueryable<string> genreQuery = from m in _context.Movie
orderby m.Genre
select m.Genre;

The SelectList of genres is created by projecting the distinct genres (we don’t want our select list to have duplicate
genres).
movieGenreVM.genres = new SelectList(await genreQuery.Distinct().ToListAsync());

Adding search by genre to the Index view

@model MovieGenreViewModel

@{
ViewData["Title"] = "Index";
}

92 Chapter 1. Topics
ASP.NET 5 Documentation, Release

<h2>Index</h2>

<p>
<a asp-action="Create">Create New</a>
</p>

<form asp-controller="Movies" asp-action="Index" method="get">


<p>
<select asp-for="movieGenre" asp-items="Model.genres">
<option value="">All</option>
</select>

Title: <input type="text" name="SearchString">


<input type="submit" value="Filter" />
</p>
</form>

<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.movies[0].Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Price)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Title)
</th>
<th></th>
</tr>
<tbody>
@foreach (var item in Model.movies)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.ID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.ID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.ID">Delete</a>
</td>
</tr>
}
</tbody>
</table>

1.2. Tutorials 93
ASP.NET 5 Documentation, Release

Test the app by searching by genre, by movie title, and by both.

Adding a New Field

By Rick Anderson
In this section you’ll use Entity Framework Code First Migrations to add a new field to the model and migrate that
change to the database.
When you use EF Code First to automatically create a database, Code First adds a table to the database to help track
whether the schema of the database is in sync with the model classes it was generated from. If they aren’t in sync, EF
throws an exception. This makes it easier to track down issues at development time that you might otherwise only find
(by obscure errors) at run time.

Adding a Rating Property to the Movie Model

Open the Models/Movie.cs file and add a Rating property:


public class Movie
{
public int ID { get; set; }
public string Title { get; set; }

[Display(Name = "Release Date")]


[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
public string Rating { get; set; }
}

Build the app (Ctrl+Shift+B).


Because you’ve added a new field to the Movie class, you also need to update the binding white list so this new
property will be included. Update the [Bind] attribute for Create and Edit action methods to include the Rating
property:
[Bind("ID,Title,ReleaseDate,Genre,Price,Rating")]

You also need to update the view templates in order to display, create and edit the new Rating property in the browser
view.
Edit the /Views/Movies/Index.cshtml file and add a Rating field:
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.movies[0].Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Price)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Title)
</th>

94 Chapter 1. Topics
ASP.NET 5 Documentation, Release

<th>
@Html.DisplayNameFor(model => model.movies[0].Rating)
</th>
<th></th>
</tr>
<tbody>
@foreach (var item in Model.movies)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>

Update the /Views/Movies/Create.cshtml with a Rating field. You can copy/paste the previous “form group” and let
intelliSense help you update the fields. IntelliSense works with Tag Helpers.

The app won’t work until we update the DB to include the new field. If you run it now, you’ll get the following
SqlException:

1.2. Tutorials 95
ASP.NET 5 Documentation, Release

You’re seeing this error because the updated Movie model class is different than the schema of the Movie table of the
existing database. (There’s no Rating column in the database table.)
There are a few approaches to resolving the error:
1. Have the Entity Framework automatically drop and re-create the database based on the new model class schema.
This approach is very convenient early in the development cycle when you are doing active development on a
test database; it allows you to quickly evolve the model and database schema together. The downside, though, is
that you lose existing data in the database — so you don’t want to use this approach on a production database!
Using an initializer to automatically seed a database with test data is often a productive way to develop an
application.
2. Explicitly modify the schema of the existing database so that it matches the model classes. The advantage of
this approach is that you keep your data. You can make this change either manually or by creating a database
change script.
3. Use Code First Migrations to update the database schema.
For this tutorial, we’ll use Code First Migrations.
Update the SeedData class so that it provides a value for the new column. A sample change is shown below, but
you’ll want to make this change for each new Movie.
new Movie
{
Title = "When Harry Met Sally",
ReleaseDate = DateTime.Parse("1989-1-11"),
Genre = "Romantic Comedy",
Rating = "R",
Price = 7.99M
},

Build the solution then open a command prompt. Enter the following commands:
dotnet ef migrations add Rating
dotnet ef database update

The migrations add command tells the migration framework to examine the current Movie model with the
current Movie DB schema and create the necessary code to migrate the DB to the new model. The name “Rating” is

96 Chapter 1. Topics
ASP.NET 5 Documentation, Release

arbitrary and is used to name the migration file. It’s helpful to use a meaningful name for the migration step.
If you delete all the records in the DB, the initialize will seed the DB and include the Rating field. You can do this
with the delete links in the browser or from SSOX.
Run the app and verify you can create/edit/display movies with a Rating field. You should also add the Rating
field to the Edit, Details, and Delete view templates.

Adding Validation

By Rick Anderson
In this this section you’ll add validation logic to the Movie model, and you’ll ensure that the validation rules are
enforced any time a user attempts to create or edit a movie.

Keeping things DRY

One of the design tenets of MVC is DRY (“Don’t Repeat Yourself”). ASP.NET MVC encourages you to specify
functionality or behavior only once, and then have it be reflected everywhere in an app. This reduces the amount of
code you need to write and makes the code you do write less error prone, easier to test, and easier to maintain.
The validation support provided by MVC and Entity Framework Core Code First is a great example of the DRY
principle in action. You can declaratively specify validation rules in one place (in the model class) and the rules are
enforced everywhere in the app.
Let’s look at how you can take advantage of this validation support in the movie app.

Adding validation rules to the movie model

Open the Movie.cs file. DataAnnotations provides a built-in set of validation attributes that you apply declaratively
to any class or property. (It also contains formatting attributes like DataType that help with formatting and don’t
provide any validation.)
Update the Movie class to take advantage of the built-in Required, StringLength, RegularExpression,
and Range validation attributes.
public class Movie
{
public int ID { get; set; }

[StringLength(60, MinimumLength = 3)]


public string Title { get; set; }

[Display(Name = "Release Date")]


[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

1.2. Tutorials 97
ASP.NET 5 Documentation, Release

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
public string Rating { get; set; }
}

The validation attributes specify behavior that you want to enforce on the model properties they are applied to. The
Required and MinimumLength attributes indicates that a property must have a value; but nothing prevents a
user from entering white space to satisfy this validation. The RegularExpression attribute is used to limit
what characters can be input. In the code above, Genre and Rating must use only letters (white space, numbers
and special characters are not allowed). The Range attribute constrains a value to within a specified range. The
StringLength attribute lets you set the maximum length of a string property, and optionally its minimum length.
Value types (such as decimal, int, float, DateTime) are inherently required and don’t need the [Required]
attribute.
Having validation rules automatically enforced by ASP.NET helps make your app more robust. It also ensures that
you can’t forget to validate something and inadvertently let bad data into the database.

Validation Error UI in MVC

Run the app and navigate to the Movies controller.


Tap the Create New link to add a new movie. Fill out the form with some invalid values. As soon as jQuery client
side validation detects the error, it displays an error message.

98 Chapter 1. Topics
ASP.NET 5 Documentation, Release

1.2. Tutorials 99
ASP.NET 5 Documentation, Release

Note: You may not be able to enter decimal points or commas in the Price field. To support jQuery validation for
non-English locales that use a comma (”,”) for a decimal point, and non US-English date formats, you must take steps
to globalize your app. See Additional resources for more information. For now, just enter whole numbers like 10.

Notice how the form has automatically rendered an appropriate validation error message in each field containing an
invalid value. The errors are enforced both client-side (using JavaScript and jQuery) and server-side (in case a user
has JavaScript disabled).
A significant benefit is that you didn’t need to change a single line of code in the MoviesController class or in
the Create.cshtml view in order to enable this validation UI. The controller and views you created earlier in this tutorial
automatically picked up the validation rules that you specified by using validation attributes on the properties of the
Movie model class. Test validation using the Edit action method, and the same validation is applied.
The form data is not sent to the server until there are no client side validation errors. You can verify this by putting a
break point in the HTTP Post method, by using the Fiddler tool , or the F12 Developer tools.

How Validation Occurs in the Create View and Create Action Method

You might wonder how the validation UI was generated without any updates to the code in the controller or views.
The next listing shows the two Create methods.
// GET: Movies/Create
public IActionResult Create()
{
return View();
}

// POST: Movies/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, fo
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("ID,Genre,Price,ReleaseDate,Title,Rating")] Movie movie
{
if (ModelState.IsValid)
{
_context.Add(movie);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(movie);
}

The first (HTTP GET) Create action method displays the initial Create form. The second ([HttpPost]) version
handles the form post. The second Create method (The HttpPost version) calls ModelState.IsValid to check
whether the movie has any validation errors. Calling this method evaluates any validation attributes that have been
applied to the object. If the object has validation errors, the Create method re-displays the form. If there are no
errors, the method saves the new movie in the database. In our movie example, the form is not posted to the server
when there are validation errors detected on the client side; the second Create method is never called when there are
client side validation errors. If you disable JavaScript in your browser, client validation is disabled and you can test
the HTTP POST Create method ModelState.IsValid detecting any validation errors.
You can set a break point in the [HttpPost] Create method and verify the method is never called, client side
validation will not submit the form data when validation errors are detected. If you disable JavaScript in your browser,
then submit the form with errors, the break point will be hit. You still get full validation without JavaScript. The
following image shows how to disable JavaScript in Internet Explorer.

100 Chapter 1. Topics


ASP.NET 5 Documentation, Release

1.2. Tutorials 101


ASP.NET 5 Documentation, Release

The following image shows how to disable JavaScript in the FireFox browser.

The following image shows how to disable JavaScript in the Chrome browser.

102 Chapter 1. Topics


ASP.NET 5 Documentation, Release

After you disable JavaScript, post invalid data and step through the debugger.

1.2. Tutorials 103


ASP.NET 5 Documentation, Release

Below is portion of the Create.cshtml view template that you scaffolded earlier in the tutorial. It’s used by the action
methods shown above both to display the initial form and to redisplay it in the event of an error.
<form asp-action="Create">
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Genre" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Genre" class="form-control" />
<span asp-validation-for="Genre" class="text-danger" />
</div>
</div>
@*Markup removed for brevity.*@
<div class="form-group">
<label asp-for="Rating" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Rating" class="form-control" />
<span asp-validation-for="Rating" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>

The Input Tag Helper consumes the DataAnnotations attributes and produces HTML attributes needed for jQuery
Validation on the client side. The Validation Tag Helper displays a validation errors. See Validation.
What’s really nice about this approach is that neither the controller nor the Create view template knows anything
about the actual validation rules being enforced or about the specific error messages displayed. The validation rules
and the error strings are specified only in the Movie class. These same validation rules are automatically applied to
the Edit view and any other views templates you might create that edit your model.
When you need to change validation logic, you can do so in exactly one place by adding validation attributes to the
model (in this example, the Movie class). You won’t have to worry about different parts of the application being
inconsistent with how the rules are enforced — all validation logic will be defined in one place and used everywhere.
This keeps the code very clean, and makes it easy to maintain and evolve. And it means that that you’ll be fully

104 Chapter 1. Topics


ASP.NET 5 Documentation, Release

honoring the DRY principle.

Using DataType Attributes

Open the Movie.cs file and examine the Movie class. The System.ComponentModel.DataAnnotations
namespace provides formatting attributes in addition to the built-in set of validation attributes. We’ve already ap-
plied a DataType enumeration value to the release date and to the price fields. The following code shows the
ReleaseDate and Price properties with the appropriate DataType attribute.
[Display(Name = "Release Date")]
[DataType(DataType.Date)]
public DateTime ReleaseDate { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }

The DataType attributes only provide hints for the view engine to format the data (and supply attributes
such as <a> for URL’s and <a href="mailto:EmailAddress.com"> for email. You can use the
RegularExpression attribute to validate the format of the data. The DataType attribute is used to specify
a data type that is more specific than the database intrinsic type, they are not validation attributes. In this case
we only want to keep track of the date, not the time. The DataType Enumeration provides for many data types,
such as Date, Time, PhoneNumber, Currency, EmailAddress and more. The DataType attribute can also enable
the application to automatically provide type-specific features. For example, a mailto: link can be created for
DataType.EmailAddress, and a date selector can be provided for DataType.Date in browsers that support
HTML5. The DataType attributes emits HTML 5 data- (pronounced data dash) attributes that HTML 5 browsers
can understand. The DataType attributes do not provide any validation.
DataType.Date does not specify the format of the date that is displayed. By default, the data field is displayed
according to the default formats based on the server’s CultureInfo.
The DisplayFormat attribute is used to explicitly specify the date format:
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }

The ApplyFormatInEditMode setting specifies that the formatting should also be applied when the value is
displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you
probably do not want the currency symbol in the text box for editing.)
You can use the DisplayFormat attribute by itself, but it’s generally a good idea to use the DataType attribute.
The DataType attribute conveys the semantics of the data as opposed to how to render it on a screen, and provides
the following benefits that you don’t get with DisplayFormat:
• The browser can enable HTML5 features (for example to show a calendar control, the locale-appropriate cur-
rency symbol, email links, etc.)
• By default, the browser will render data using the correct format based on your locale
• The DataType attribute can enable MVC to choose the right field template to render the data (the
DisplayFormat if used by itself uses the string template). For more information, see Brad Wilson’s
ASP.NET MVC 2 Templates. (Though written for MVC 2, this article still applies to the current version of
ASP.NET MVC.)

Note: jQuery validation does not work with the Range attribute and DateTime. For example, the following code
will always display a client side validation error, even when the date is in the specified range:

1.2. Tutorials 105


ASP.NET 5 Documentation, Release

[Range(typeof(DateTime), "1/1/1966", "1/1/2020")]

You will need to disable jQuery date validation to use the Range attribute with DateTime. It’s generally not a good
practice to compile hard dates in your models, so using the Range attribute and DateTime is discouraged.
The following code shows combining attributes on one line:
public class Movie
{
public int ID { get; set; }

[StringLength(60, MinimumLength = 3)]


public string Title { get; set; }

[Display(Name = "Release Date"), DataType(DataType.Date)]


public DateTime ReleaseDate { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$"), Required, StringLength(30)]


public string Genre { get; set; }

[Range(1, 100), DataType(DataType.Currency)]


public decimal Price { get; set; }

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$"), StringLength(5)]
public string Rating { get; set; }
}

In the next part of the series, we’ll review the application and make some improvements to the automatically generated
Details and Delete methods.

Additional resources

• Working with Forms


• Globalization and localization
• Introduction to Tag Helpers
• Authoring Tag Helpers

Examining the Details and Delete methods

By Rick Anderson
Open the Movie controller and examine the Details method:
// GET: Movies/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}

var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);


if (movie == null)
{
return NotFound();

106 Chapter 1. Topics


ASP.NET 5 Documentation, Release

return View(movie);
}

The MVC scaffolding engine that created this action method adds a comment showing a HTTP request that invokes
the method. In this case it’s a GET request with three URL segments, the Movies controller, the Details method
and a id value. Recall these segments are defined in Startup.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});

Code First makes it easy to search for data using the SingleOrDefaultAsync method. An important security
feature built into the method is that the code verifies that the search method has found a movie before the code tries
to do anything with it. For example, a hacker could introduce errors into the site by changing the URL created
by the links from http://localhost:xxxx/Movies/Details/1 to something like http://localhost:xxxx/Movies/Details/12345
(or some other value that doesn’t represent an actual movie). If you did not check for a null movie, the app would
throw an exception.
Examine the Delete and DeleteConfirmed methods.
// GET: Movies/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}

var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);


if (movie == null)
{
return NotFound();
}

return View(movie);
}

// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
_context.Movie.Remove(movie);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}

Note that the HTTP GET Delete method doesn’t delete the specified movie, it returns a view of the movie where
you can submit (HttpPost) the deletion. Performing a delete operation in response to a GET request (or for that matter,
performing an edit operation, create operation, or any other operation that changes data) opens up a security hole.
The [HttpPost] method that deletes the data is named DeleteConfirmed to give the HTTP POST method a
unique signature or name. The two method signatures are shown below:

1.2. Tutorials 107


ASP.NET 5 Documentation, Release

// GET: Movies/Delete/5
public async Task<IActionResult> Delete(int? id)

// POST: Movies/Delete/5
public async Task<IActionResult> DeleteConfirmed(int id)

The common language runtime (CLR) requires overloaded methods to have a unique parameter signature (same
method name but different list of parameters). However, here you need two Delete methods – one for GET and
one for POST – that both have the same parameter signature. (They both need to accept a single integer as a parame-
ter.)
There are two approaches to this problem, one is to give the methods different names. That’s what the scaffolding
mechanism did in the preceding example. However, this introduces a small problem: ASP.NET maps segments of
a URL to action methods by name, and if you rename a method, routing normally wouldn’t be able to find that
method. The solution is what you see in the example, which is to add the ActionName("Delete") attribute to the
DeleteConfirmed method. That attribute performs mapping for the routing system so that a URL that includes
/Delete/ for a POST request will find the DeleteConfirmed method.
Another common work around for methods that have identical names and signatures is to artificially change the
signature of the POST method to include an extra (unused) parameter. That’s what we did in a previous post when we
added the notUsed parameter. You could do the same thing here for the [HttpPost] Delete method:
// POST: Movies/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, bool notUsed)
{
var movie = await _context.Movie.SingleOrDefaultAsync(m => m.ID == id);
_context.Movie.Remove(movie);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}

1.2.4 Publish to an Azure Web App using Visual Studio

By Erik Reitan
This article describes how to publish an ASP.NET web app to Azure using Visual Studio.
Note: To complete this tutorial, you need a Microsoft Azure account. If you don’t have an account, you can activate
your MSDN subscriber benefits or sign up for a free trial.
Start by either creating a new ASP.NET web app or opening an existing ASP.NET web app.
1. In Solution Explorer of Visual Studio, right-click on the project and select Publish.

108 Chapter 1. Topics


ASP.NET 5 Documentation, Release

2. In the Publish Web dialog box, click on Microsoft Azure Web Apps and log into your Azure subscription.

1.2. Tutorials 109


ASP.NET 5 Documentation, Release

3. Click New in the Select Existing Web App dialog box to create a new Web app in Azure.

4. Enter a site name and region. You can optionally create a new database server, however if you’ve created a
database server in the past, use that. When you’re ready to continue, click Create.

110 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Database servers are a precious resource. For test and development it’s best to use an existing server. There is no
validation on the database password, so if you enter an incorrect value, you won’t get an error until your web app
attempts to access the database.
5. On the Connection tab of the Publish Web dialog box, click Publish.

1.2. Tutorials 111


ASP.NET 5 Documentation, Release

You can view the publishing progress in the Web Publish Activity window within Visual Studio.

When publishing to Azure is complete, your web app will be displayed in a browser running on Azure.

112 Chapter 1. Topics


ASP.NET 5 Documentation, Release

1.2.5 ASP.NET Core on Nano Server

By Sourabh Shirhatti

1.2. Tutorials 113


ASP.NET 5 Documentation, Release

Attention: This tutorial uses a pre-release version of the Nano Server installation option of Windows
Server Technical Preview 4. You may use the software in the virtual hard disk image only to internally
demonstrate and evaluate it. You may not use the software in a live operating environment. Please see
https://go.microsoft.com/fwlink/?LinkId=624232 for specific information about the end date for the preview.

In this tutorial, you’ll take an existing ASP.NET Core app and deploy it to a Nano Server instance running IIS.

Sections:
• Introduction
• Setting up the Nano Server Instance
• Installing the HttpPlatformHandler Module
• Enabling the HttpPlatformHandler
• Publishing the application
• Open a Port in the Firewall
• Running the Application

Introduction

Windows Server 2016 Technical Preview offers a new installation option: Nano Server. Nano Server is a remotely
administered server operating system optimized for private clouds and datacenters. It takes up far less disk space, sets
up significantly faster, and requires far fewer updates and restarts than Windows Server. You can learn more about
Nano Server from the official docs.
In this tutorial, we will be using the pre-built Virtual Hard Disk (VHD) for Nano Server from Windows Server Tech-
nical Preview 4. This pre-built VHD already includes the Reverse Forwarders and IIS packages which are required for
this tutorial.
Before proceeding with this tutorial, you will need the published output of an existing ASP.NET Core application.
Ensure your application is built to run in a 64-bit process.

Setting up the Nano Server Instance

Create a new Virtual Machine using Hyper-V on your development machine using the previously downloaded VHD.
The machine will require you to set an administator password before logging on. At the VM console, press F11 to set
the password before the first logon.
After setting the local password, you will manage Nano Server using PowerShell remoting.

Connecting to your Nano Server Instance using PowerShell Remoting

Open an elevated PowerShell window to add your remote Nano Server instance to your TrustedHosts list.
$ip = "10.83.181.14" # replace with the correct IP address
Set-Item WSMan:\localhost\Client\TrustedHosts "$ip" -Concatenate -Force

Once you have added your Nano Server instance to your TrustedHosts, you can connect to it using PowerShell
remoting
$ip = "10.83.181.14" # replace with the correct IP address
$s = New-PSSession -ComputerName $ip -Credential ~\Administrator
Enter-PSSession $s

114 Chapter 1. Topics


ASP.NET 5 Documentation, Release

If you have successfully connected then your prompt will look like this [10.83.181.14]: PS
C:\Users\Administrator\Documents>

Installing the HttpPlatformHandler Module

The HttpPlatformHandler is an IIS 7.5+ module which is responsible for process management of HTTP listeners and
to proxy requests to processes that it manages. At the moment, the process to install the HttpPlatformHandler Module
for IIS is manual. You will need to install the latest 64-bit version of the HttpPlatformHandler on a regular (not Nano)
machine. After installing you will need to copy the following files:
• %windir%\System32\inetsrv\HttpPlatformHandler.dll
• %windir%\System32\inetsrv\config\schema\httpplatform_schema.xml
On the Nano machine you’ll need to copy those two files to their respective locations.
Copy-Item .\HttpPlatformHandler.dll c:\Windows\System32\inetsrv
Copy-Item .\httpplatform_schema.xml c:\Windows\System32\inetsrv\config\schema

Enabling the HttpPlatformHandler

You can execute the following PowerShell script in a remote PowerShell session to enable the HttpPlatformHandler
module on the Nano server.

Note: This script runs on a clean system, but is not meant to be idempotent. If you run this multiple times it
will add multiple entries. If you end up in a bad state, you can find backups of the applicationHost.config file at
%systemdrive%inetpubhistory.

Import-Module IISAdministration

$sm = Get-IISServerManager

# Add AppSettings section (for Asp.Net Core)


$sm.GetApplicationHostConfiguration().RootSectionGroup.Sections.Add("appSettings")

# Unlock handlers section


$appHostconfig = $sm.GetApplicationHostConfiguration()
$section = $appHostconfig.GetSection("system.webServer/handlers")
$section.OverrideMode="Allow"

# Add httpPlatform section to system.webServer


$sectionHttpPlatform = $appHostConfig.RootSectionGroup.SectionGroups["system.webServer"].Sections.Add
$sectionHttpPlatform.OverrideModeDefault = "Allow"

# Add to globalModules
$globalModules = Get-IISConfigSection "system.webServer/globalModules" | Get-IISConfigCollection
New-IISConfigCollectionElement $globalModules -ConfigAttribute @{"name"="httpPlatformHandler";"image"

# Add to modules
$modules = Get-IISConfigSection "system.webServer/modules" | Get-IISConfigCollection
New-IISConfigCollectionElement $modules -ConfigAttribute @{"name"="httpPlatformHandler"}
$sm.CommitChanges()

1.2. Tutorials 115


ASP.NET 5 Documentation, Release

Manually Editing applicationHost.config

You can skip this section if you already ran the PowerShell script above. Though is not recommended, you can
alternatively enable the HttpPlatformHandler by manually editing the applicationHost.config file.
Open up C:\Windows\System32\inetsrv\config\applicationHost.config
Under <configSections> add
<configSections>
<section name="appSettings" />

In the system.webServer section group, update the handlers section to allow the configured handlers to be over-
ridden.
<sectionGroup name="system.webServer">
<section name="handlers" overrideModeDefault="Allow" />

Add httpPlatformHandler to the globalModules section


<globalModules>
<add name="httpPlatformHandler" image="%SystemRoot%\system32\inetsrv\httpPlatformHandler.dll" />

Additionally, add httpPlatformHandler to the modules section


<modules>
<add name="httpPlatformHandler" />

Publishing the application

Copy over the published output of your existing application to the Nano server.
$ip = "10.83.181.14" # replace with the correct IP address
$s = New-PSSession -ComputerName $ip -Credential ~\Administrator
Copy-Item -ToSession $s -Path <path-to-src>\bin\output\ -Destination C:\HelloAspNet5 -Recurse

Use the following PowerShell snippet to create a new site in IIS for our published app. This script uses the
DefaultAppPool for simplicity. For more considerations on running under an application pool, see Application
Pools.
Import-module IISAdministration
New-IISSite -Name "AspNet5" -PhysicalPath c:\HelloAspNet5\wwwroot -BindingInformation "*:8000:"

Manually Editing applicationHost.config

You can also create the site by manually editing the applicationHost.config file.
<sites>
<site name="AspNet5" id="2">
<application path="/">
<virtualDirectory path="/" physicalPath="C:\HelloAspNet5\wwwroot" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:8000:" />
</bindings>
</site>
</sites>

116 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Open a Port in the Firewall

Since we have IIS listening on port 8000 and forwarding request to our application, we will need open up the port to
TCP traffic.
New-NetFirewallRule -Name "AspNet5" -DisplayName "HTTP on TCP/8000" -Protocol TCP -LocalPort 8000 -Ac

Running the Application

At this point your published web application, should be accessible in browser by visiting
http://<ip-address>:8000. If you have set up logging as described in Log Redirection, you should
be able to view your logs at C:\HelloAspNet5\logs.

1.2.6 Creating Backend Services for Native Mobile Applications

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

1.3 Conceptual Overview

1.3.1 Introduction to ASP.NET Core

By Daniel Roth
ASP.NET Core is a significant redesign of ASP.NET. This topic introduces the new concepts in ASP.NET Core and
explains how they help you develop modern web apps.

Sections:
• What is ASP.NET Core?
• Why build ASP.NET Core?
• Application anatomy
• Services
• Middleware
• Servers
• Web root
• Configuration
• Client-side development

What is ASP.NET Core?

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based Web applications
using .NET. We built it from the ground up to provide an optimized development framework for apps that are either

1.3. Conceptual Overview 117


ASP.NET 5 Documentation, Release

deployed to the cloud or run on-premises. It consists of modular components with minimal overhead, so you retain
flexibility while constructing your solutions. You can develop and run your ASP.NET Core applications cross-platform
on Windows, Mac and Linux. ASP.NET Core is fully open source on GitHub.

Why build ASP.NET Core?

The first preview release of ASP.NET came out almost 15 years ago as part of the .NET Framework. Since then
millions of developers have used it to build and run great web applications, and over the years we have added and
evolved many, many capabilities to it.
With ASP.NET Core we are making a number of architectural changes that make the core web framework much leaner
and more modular. ASP.NET Core is no longer based on System.Web.dll, but is instead based on a set of granular
and well factored NuGet packages allowing you to optimize your app to have just what you need. You can reduce the
surface area of your application to improve security, reduce your servicing burden and also to improve performance in
a true pay-for-what-you-use model.
ASP.NET Core is built with the needs of modern Web applications in mind, including a unified story for building Web
UI and Web APIs that integrate with today’s modern client-side frameworks and development workflows. ASP.NET
Core is also built to be cloud-ready by introducing environment-based configuration and by providing built-in depen-
dency injection support.
To appeal to a broader audience of developers, ASP.NET Core supports cross-platform development on Windows, Mac
and Linux. The entire ASP.NET Core stack is open source and encourages community contributions and engagement.
ASP.NET Core comes with a new, agile project system in Visual Studio while also providing a complete command-line
interface so that you can develop using the tools of your choice.
In summary, with ASP.NET Core you gain the following foundational improvements:
• New light-weight and modular HTTP request pipeline
• Ability to host on IIS or self-host in your own process
• Built on .NET Core, which supports true side-by-side app versioning
• Ships entirely as NuGet packages
• Integrated support for creating and using NuGet packages
• Single aligned web stack for Web UI and Web APIs
• Cloud-ready environment-based configuration
• Built-in support for dependency injection
• New tooling that simplifies modern web development
• Build and run cross-platform ASP.NET apps on Windows, Mac and Linux
• Open source and community focused

Application anatomy

ASP.NET Core applications are defined using a public Startup class:


public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}

public void Configure(IApplicationBuilder app)

118 Chapter 1. Topics


ASP.NET 5 Documentation, Release

{
}
}

The ConfigureServices method defines the services used by your application and the Configure method is
used to define what middleware makes up your request pipeline. See Application Startup for more details.

Services

A service is a component that is intended for common consumption in an application. Services are made available
through dependency injection. ASP.NET Core includes a simple built-in inversion of control (IoC) container that sup-
ports constructor injection by default, but can be easily replaced with your IoC container of choice. See Dependency
Injection for more details.
Services in ASP.NET Core come in three varieties: singleton, scoped and transient. Transient services are created each
time they’re requested from the container. Scoped services are created only if they don’t already exist in the current
scope. For Web applications, a container scope is created for each request, so you can think of scoped services as per
request. Singleton services are only ever created once.

Middleware

In ASP.NET Core you compose your request pipeline using Middleware. ASP.NET Core middleware perform asyn-
chronous logic on an HttpContext and then optionally invoke the next middleware in the sequence or termi-
nate the request directly. You generally “Use” middleware by invoking a corresponding extension method on the
IApplicationBuilder in your Configure method.
ASP.NET Core comes with a rich set of prebuilt middleware:
• Working with Static Files
• Routing
• Diagnostics
• Authentication
You can also author your own custom middleware.
You can use any OWIN-based middleware with ASP.NET Core. See OWIN for details.

Servers

The ASP.NET Core hosting model does not directly listen for requests, but instead relies on an HTTP server implemen-
tation to surface the request to the application as a set of feature interfaces that can be composed into an HttpContext.
ASP.NET Core includes a managed cross-platform web server, called Kestrel, that you would typically run behind a
production web server like IIS or nginx.

Web root

The Web root of your application is the root location in your project from which HTTP requests are handled (ex.
handling of static file requests). The Web root of an ASP.NET Core application is configured using the “webroot”
property in your project.json file.

1.3. Conceptual Overview 119


ASP.NET 5 Documentation, Release

Configuration

ASP.NET Core uses a new configuration model for handling of simple name-value pairs that is not based on Sys-
tem.Configuration or web.config. This new configuration model pulls from an ordered set of configuration providers.
The built-in configuration providers support a variety of file formats (XML, JSON, INI) and also environment variables
to enable environment-based configuration. You can also write your own custom configuration providers. Environ-
ments, like Development and Production, are a first-class notion in ASP.NET Core and can also be set up using
environment variables:
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532
builder.AddUserSecrets();
}

builder.AddEnvironmentVariables();
Configuration = builder.Build();

See Configuration for more details on the new configuration system and Working with Multiple Environments for
details on how to work with environments in ASP.NET Core.

Client-side development

ASP.NET Core is designed to integrate seamlessly with a variety of client-side frameworks, including AngularJS,
KnockoutJS and Bootstrap. See Client-Side Development for more details.

1.3.2 Choosing the Right .NET For You on the Server

By Daniel Roth
ASP.NET Core is based on the .NET Core project model, which supports building applications that can run cross-
platform on Windows, Mac and Linux. When building a .NET Core project you also have a choice of which .NET
flavor to target your application at: .NET Framework (CLR), .NET Core (CoreCLR) or Mono. Which .NET flavor
should you choose? Let’s look at the pros and cons of each one.

.NET Framework

The .NET Framework is the most well known and mature of the three options. The .NET Framework is a mature
and fully featured framework that ships with Windows. The .NET Framework ecosystem is well established and has
been around for well over a decade. The .NET Framework is production ready today and provides the highest level of
compatibility for your existing applications and libraries.
The .NET Framework runs on Windows only. It is also a monolithic component with a large API surface area and a
slower release cycle. While the code for the .NET Framework is available for reference it is not an active open source
project.

120 Chapter 1. Topics


ASP.NET 5 Documentation, Release

.NET Core

.NET Core is a modular runtime and library implementation that includes a subset of the .NET Framework. .NET
Core is supported on Windows, Mac and Linux. .NET Core consists of a set of libraries, called “CoreFX”, and a
small, optimized runtime, called “CoreCLR”. .NET Core is open-source, so you can follow progress on the project
and contribute to it on GitHub.
The CoreCLR runtime (Microsoft.CoreCLR) and CoreFX libraries are distributed via NuGet. Because .NET Core has
been built as a componentized set of libraries you can limit the API surface area your application uses to just the pieces
you need. You can also run .NET Core based applications on much more constrained environments (ex. Windows
Server Nano).
The API factoring in .NET Core was updated to enable better componentization. This means that existing libraries
built for the .NET Framework generally need to be recompiled to run on .NET Core. The .NET Core ecosystem is
relatively new, but it is rapidly growing with the support of popular .NET packages like JSON.NET, AutoFac, xUnit.net
and many others.
Developing on .NET Core allows you to target a single consistent platform that can run on multiple platforms.

Mono

Mono is a port of the .NET Framework built primarily for non-Windows platforms. Mono is open source and cross-
platform. It also shares a similar API factoring to the .NET Framework, so many existing managed libraries work on
Mono today. Mono is a good proving ground for cross-platform development while cross-platform support in .NET
Core matures.

Summary

The .NET Core project model makes .NET development available for more scenarios than ever before. With .NET
Core you have the option to target your application at existing available .NET platforms. Which .NET flavor you pick
will depend on your specific scenarios, timelines, feature requirements and compatibility requirements.

1.4 Fundamentals

1.4.1 Application Startup

By Steve Smith
ASP.NET Core provides complete control of how individual requests are handled by your application. The Startup
class is the entry point to the application, setting up configuration and wiring up services the application will use. De-
velopers configure a request pipeline in the Startup class that is used to handle all requests made to the application.

Sections:
• The Startup class
• The Configure method
• The ConfigureServices method
• Services Available in Startup
• Additional Resources

1.4. Fundamentals 121


ASP.NET 5 Documentation, Release

The Startup class

In ASP.NET Core, the Startup class provides the entry point for an application, and is required for all applications.
It’s possible to have environment-specific startup classes and methods (see Working with Multiple Environments),
but regardless, one Startup class will serve as the entry point for the application. ASP.NET searches the primary
assembly for a class named Startup (in any namespace). You can specify a different assembly to search using
the Hosting:Application configuration key. It doesn’t matter whether the class is defined as public; ASP.NET will
still load it if it conforms to the naming convention. If there are multiple Startup classes, this will not trigger an
exception. ASP.NET will select one based on its namespace (matching the project’s root namespace first, otherwise
using the class in the alphabetically first namespace).
The Startup class can optionally accept dependencies in its constructor that are provided through dependency
injection. Typically, the way an application will be configured is defined within its Startup class’s constructor
(see Configuration). The Startup class must define a Configure method, and may optionally also define a
ConfigureServices method, which will be called when the application is started.

The Configure method

The Configure method is used to specify how the ASP.NET application will respond to individual HTTP requests.
At its simplest, you can configure every request to receive the same response. However, most real-world applications
require more functionality than this. More complex sets of pipeline configuration can be encapsulated in middleware
and added using extension methods on IApplicationBuilder.
Your Configure method must accept an IApplicationBuilder parameter. Additional services, like
IHostingEnvironment and ILoggerFactory may also be specified, in which case these services will be
injected by the server if they are available. In the following example from the default web site template, you can see
several extension methods are used to configure the pipeline with support for BrowserLink, error pages, static files,
ASP.NET MVC, and Identity.
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
2 {
3 loggerFactory.AddConsole(Configuration.GetSection("Logging"));
4 loggerFactory.AddDebug();
5

6 if (env.IsDevelopment())
7 {
8 app.UseDeveloperExceptionPage();
9 app.UseDatabaseErrorPage();
10 app.UseBrowserLink();
11 }
12 else
13 {
14 app.UseExceptionHandler("/Home/Error");
15 }
16

17 app.UseStaticFiles();
18

19 app.UseIdentity();
20

21 // Add external authentication middleware below. To configure them please see http://go.microsoft
22

23 app.UseMvc(routes =>
24 {
25 routes.MapRoute(
26 name: "default",
27 template: "{controller=Home}/{action=Index}/{id?}");

122 Chapter 1. Topics


ASP.NET 5 Documentation, Release

28 });
29 }

Each Use extension method adds middleware to the request pipeline. For instance, the UseMvc extension method
adds the routing middleware to the request pipeline and configures MVC as the default handler.
You can learn all about middleware and using IApplicationBuilder to define your request pipeline in the Middleware
topic.

The ConfigureServices method

Your Startup class can optionally include a ConfigureServices method for configuring services that are
used by your application. The ConfigureServices method is a public method on your Startup class
that takes an IServiceCollection instance as a parameter and optionally returns an IServiceProvider. The
ConfigureServices method is called before Configure. This is important, because some features like
ASP.NET MVC require certain services to be added in ConfigureServices before they can be wired up to
the request pipeline.
Just as with Configure, it is recommended that features that require substantial setup within
ConfigureServices be wrapped up in extension methods on IServiceCollection. You can see in this ex-
ample from the default web site template that several Add[Something] extension methods are used to configure
the app to use services from Entity Framework, Identity, and MVC:
1 public void ConfigureServices(IServiceCollection services)
2 {
3 // Add framework services.
4 services.AddDbContext<ApplicationDbContext>(options =>
5 options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
6

7 services.AddIdentity<ApplicationUser, IdentityRole>()
8 .AddEntityFrameworkStores<ApplicationDbContext>()
9 .AddDefaultTokenProviders();
10

11 services.AddMvc();
12

13 // Add application services.


14 services.AddTransient<IEmailSender, AuthMessageSender>();
15 services.AddTransient<ISmsSender, AuthMessageSender>();
16 }

Adding services to the services container makes them available within your application via dependency injection. Just
as the Startup class is able to specify dependencies its methods require as parameters, rather than hard-coding to a
specific implementation, so too can your middleware, MVC controllers and other classes in your application.
The ConfigureServices method is also where you should add configuration option classes, like AppSettings
in the example above, that you would like to have available in your application. See the Configuration topic to learn
more about configuring options.

Services Available in Startup

ASP.NET Core provides certain application services and objects during your application’s startup. You can request
certain sets of these services by simply including the appropriate interface as a parameter on your Startup class’s
constructor or one of its Configure or ConfigureServices methods. The services available to each method in
the Startup class are described below. The framework services and objects include:

1.4. Fundamentals 123


ASP.NET 5 Documentation, Release

IApplicationBuilder Used to build the application request pipeline. Available only to the Configure method in
Startup. Learn more about Request Features.
IApplicationEnvironment Provides access to the application properties, such as ApplicationName,
ApplicationVersion, and ApplicationBasePath. Available to the Startup constructor and
Configure method.
IHostingEnvironment Provides the current EnvironmentName, WebRootPath, and web root file provider.
Available to the Startup constructor and Configure method.
ILoggerFactory Provides a mechanism for creating loggers. Available to the Startup constructor and
Configure method. Learn more about Logging.
IServiceCollection The current set of services configured in the container. Available only to the
ConfigureServices method, and used by that method to configure the services available to an applica-
tion.
Looking at each method in the Startup class in the order in which they are called, the following services may be
requested as parameters:
Startup Constructor - IApplicationEnvironment - IHostingEnvironment - ILoggerFactory
ConfigureServices - IServiceCollection
Configure - IApplicationBuilder - IApplicationEnvironment - IHostingEnvironment -
ILoggerFactory

Note: Although ILoggerFactory is available in the constructor, it is typically configured in the Configure
method. Learn more about Logging.

Additional Resources

• Working with Multiple Environments


• Middleware
• OWIN

1.4.2 Middleware

By Steve Smith and Rick Anderson

Sections:
• What is middleware
• Creating a middleware pipeline with IApplicationBuilder
• Built-in middleware
• Writing middleware
• Additional Resources

View or download sample code

What is middleware

Middleware are software components that are assembled into an application pipeline to handle requests and responses.
Each component chooses whether to pass the request on to the next component in the pipeline, and can perform certain

124 Chapter 1. Topics


ASP.NET 5 Documentation, Release

actions before and after the next component is invoked in the pipeline. Request delegates are used to build the request
pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run, Map, and Use extension methods on the IApplicationBuilder type that is
passed into the Configure method in the Startup class. An individual request delegate can be specified in-line as
an anonymous method, or it can be defined in a reusable class. These reusable classes are middleware, or middleware
components. Each middleware component in the request pipeline is responsible for invoking the next component in
the pipeline, or short-circuiting the chain if appropriate.
Migrating HTTP Modules to Middleware explains the difference between request pipelines in ASP.NET Core and the
previous versions and provides more middleware samples.

Creating a middleware pipeline with IApplicationBuilder

The ASP.NET request pipeline consists of a sequence of request delegates, called one after the next, as this diagram
shows (the thread of execution follows the black arrows):

Each delegate has the opportunity to perform operations before and after the next delegate. Any delegate can choose
to stop passing the request on to the next delegate, and instead handle the request itself. This is referred to as short-
circuiting the request pipeline, and is desirable because it allows unnecessary work to be avoided. For example, an
authorization middleware might only call the next delegate if the request is authenticated; otherwise it could short-
circuit the pipeline and return a “Not Authorized” response. Exception handling delegates need to be called early on
in the pipeline, so they are able to catch exceptions that occur in deeper calls within the pipeline.
You can see an example of setting up the request pipeline in the default web site template that ships with Visual Studio
2015. The Configure method adds the following middleware components:
1. Error handling (for both development and non-development environments)
2. IIS HttpPlatformHandler reverse proxy module. This module handles forwarded Windows Authentication, re-
quest schemes, remote IPs, and so on.

1.4. Fundamentals 125


ASP.NET 5 Documentation, Release

3. Static file server


4. Authentication
5. MVC
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseIdentity();

// Add external authentication middleware below. To configure them please see http://go.microsoft

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}

In the code above (in non-development environments), UseExceptionHandler is the first middleware added to the
pipeline, therefore will catch any exceptions that occur in later calls.
The static file module provides no authorization checks. Any files served by it, including those under wwwroot are
publicly available. If you want to serve files based on authorization:
1. Store them outside of wwwroot and any directory accessible to the static file middleware.
2. Deliver them through a controller action, returning a FileResult where authorization is applied.
A request that is handled by the static file module will short circuit the pipeline. (see Working with Static Files.) If the
request is not handled by the static file module, it’s passed on to the Identity module, which performs authentication.
If the request is not authenticated, the pipeline is short circuited. If the request does not fail authentication, the last
stage of this pipeline is called, which is the MVC framework.

Note: The order in which you add middleware components is generally the order in which they take effect on the
request, and then in reverse for the response. This can be critical to your app’s security, performance and function-
ality. In the code above, the static file middleware is called early in the pipeline so it can handle requests and short
circuit without going through unnecessary components. The authentication middleware is added to the pipeline be-
fore anything that handles requests that need to be authenticated. Exception handling must be registered before other
middleware components in order to catch exceptions thrown by those components.

The simplest possible ASP.NET application sets up a single request delegate that handles all requests. In this case,
there isn’t really a request “pipeline”, so much as a single anonymous function that is called in response to every HTTP

126 Chapter 1. Topics


ASP.NET 5 Documentation, Release

request.
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});

The first App.Run delegate terminates the pipeline. In the following example, only the first delegate (“Hello, World!”)
will run.
public void Configure(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello, World!");
});

app.Run(async context =>


{
await context.Response.WriteAsync("Hello, World, Again!");
});

You chain multiple request delegates together; the next parameter represents the next delegate in the pipeline. You
can terminate (short-circuit) the pipeline by not calling the next parameter. You can typically perform actions both
before and after the next delegate, as this example demonstrates:
public void ConfigureLogInline(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information);
var logger = loggerfactory.CreateLogger(_environment);
app.Use(async (context, next) =>
{
logger.LogInformation("Handling request.");
await next.Invoke();
logger.LogInformation("Finished handling request.");
});

app.Run(async context =>


{
await context.Response.WriteAsync("Hello from " + _environment);
});
}

Warning: Avoid modifying HttpResponse after invoking next, one of the next components in the pipeline
may have written to the response, causing it to be sent to the client.

Note: This ConfigureLogInline method is called when the application is run with an environment set
to LogInline. Learn more about Working with Multiple Environments. We will be using variations of
Configure[Environment] to show different options in the rest of this article. The easiest way to run the samples
in Visual Studio is with the web command, which is configured in project.json. See also Application Startup.

In the above example, the call to await next.Invoke() will call into the next delegate await
context.Response.WriteAsync("Hello from " + _environment);. The client will receive the ex-
pected response (“Hello from LogInline”), and the server’s console output includes both the before and after messages:

1.4. Fundamentals 127


ASP.NET 5 Documentation, Release

Run, Map, and Use

You configure the HTTP pipeline using Run, Map, and Use. The Run method short circuits the pipeline (that is, it will
not call a next request delegate). Thus, Run should only be called at the end of your pipeline. Run is a convention,
and some middleware components may expose their own Run[Middleware] methods that should only run at the end
of the pipeline. The following two middleware are equivalent as the Use version doesn’t use the next parameter:
public void ConfigureEnvironmentOne(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
}

public void ConfigureEnvironmentTwo(IApplicationBuilder app)


{
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("Hello from " + _environment);
});
}

Note: The IApplicationBuilder interface exposes a single Use method, so technically they’re not all extension
methods.

We’ve already seen several examples of how to build a request pipeline with Use. Map* extensions are used as a
convention for branching the pipeline. The current implementation supports branching based on the request’s path, or
using a predicate. The Map extension method is used to match request delegates based on a request’s path. Map simply
accepts a path and a function that configures a separate middleware pipeline. In the following example, any request
with the base path of /maptest will be handled by the pipeline configured in the HandleMapTest method.

128 Chapter 1. Topics


ASP.NET 5 Documentation, Release

private static void HandleMapTest(IApplicationBuilder app)


{
app.Run(async context =>
{
await context.Response.WriteAsync("Map Test Successful");
});
}

public void ConfigureMapping(IApplicationBuilder app)


{
app.Map("/maptest", HandleMapTest);

Note: When Map is used, the matched path segment(s) are removed from HttpRequest.Path and appended to
HttpRequest.PathBase for each request.

In addition to path-based mapping, the MapWhen method supports predicate-based middleware branching, allowing
separate pipelines to be constructed in a very flexible fashion. Any predicate of type Func<HttpContext, bool>
can be used to map requests to a new branch of the pipeline. In the following example, a simple predicate is used to
detect the presence of a query string variable branch:
private static void HandleBranch(IApplicationBuilder app)
{
app.Run(async context =>
{
await context.Response.WriteAsync("Branch used.");
});
}

public void ConfigureMapWhen(IApplicationBuilder app)


{
app.MapWhen(context => {
return context.Request.Query.ContainsKey("branch");
}, HandleBranch);

app.Run(async context =>


{
await context.Response.WriteAsync("Hello from " + _environment);
});
}

Using the configuration shown above, any request that includes a query string value for branch will use the pipeline
defined in the HandleBranch method (in this case, a response of “Branch used.”). All other requests (that do not
define a query string value for branch) will be handled by the delegate defined on line 17.
You can also nest Maps:
app.Map("/level1", level1App => {
level1App.Map("/level2a", level2AApp => {
// "/level1/level2a"
//...
});
level1App.Map("/level2b", level2BApp => {
// "/level1/level2b"
//...
});
});

1.4. Fundamentals 129


ASP.NET 5 Documentation, Release

Built-in middleware

ASP.NET ships with the following middleware components:

Table 1.1: Middleware


Middleware Description
Authentication Provides authentication support.
CORS Configures Cross-Origin Resource Sharing.
Diagnostics Includes support for error pages and runtime information.
Routing Define and constrain request routes.
Session Provides support for managing user sessions.
Static Files Provides support for serving static files, and directory browsing.

Writing middleware

The CodeLabs middleware tutorial provides a good introduction to writing middleware.


For more complex request handling functionality, the ASP.NET team recommends implementing the middleware in its
own class, and exposing an IApplicationBuilder extension method that can be called from the Configure
method. The simple logging middleware shown in the previous example can be converted into a middleware class that
takes in the next RequestDelegate in its constructor and supports an Invoke method as shown:

Listing 1.1: RequestLoggerMiddleware.cs


using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.Logging;
using System.Threading.Tasks;

namespace MiddlewareSample
{
public class RequestLoggerMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public RequestLoggerMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)


{
_next = next;
_logger = loggerFactory.CreateLogger<RequestLoggerMiddleware>();
}

public async Task Invoke(HttpContext context)


{
_logger.LogInformation("Handling request: " + context.Request.Path);
await _next.Invoke(context);
_logger.LogInformation("Finished handling request.");
}
}
}

The middleware follows the Explicit Dependencies Principle and exposes all of its dependencies in its constructor.
Middleware can take advantage of the UseMiddleware<T> extension to inject services directly into their constructors,
as shown in the example below. Dependency injected services are automatically filled, and the extension takes a
params array of arguments to be used for non-injected parameters.

130 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Listing 1.2: RequestLoggerExtensions.cs


public static class RequestLoggerExtensions
{
public static IApplicationBuilder UseRequestLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestLoggerMiddleware>();
}
}

Using the extension method and associated middleware class, the Configure method becomes very simple and
readable.
public void ConfigureLogMiddleware(IApplicationBuilder app,
ILoggerFactory loggerfactory)
{
loggerfactory.AddConsole(minLevel: LogLevel.Information);

app.UseRequestLogger();

app.Run(async context =>


{
await context.Response.WriteAsync("Hello from " + _environment);
});
}

Although RequestLoggerMiddleware requires an ILoggerFactory parameter in its constructor, neither


the Startup class nor the UseRequestLogger extension method need to explicitly supply it. Instead, it is
automatically provided through dependency injection performed within UseMiddleware<T>.
Testing the middleware (by setting the Hosting:Environment environment variable to LogMiddleware)
should result in output like the following (when using WebListener):

Note: The UseStaticFiles extension method (which creates the StaticFileMiddleware) also uses
UseMiddleware<T>. In this case, the StaticFileOptions parameter is passed in, but other construc-
tor parameters are supplied by UseMiddleware<T> and dependency injection.

1.4. Fundamentals 131


ASP.NET 5 Documentation, Release

Additional Resources

• CodeLabs middleware tutorial


• Sample code used in this doc
• Migrating HTTP Modules to Middleware
• Application Startup
• Request Features

1.4.3 Working with Static Files

By Tom Archer
Static files, which include HTML files, CSS files, image files, and JavaScript files, are assets that the app will serve
directly to clients. In this article, we’ll cover the following topics as they relate to ASP.NET Core and static files.

Sections
• Serving static files
• Enabling directory browsing
• Serving a default document
• Using the UseFileServer method
• Working with content types
• IIS Considerations
• Best practices
• Summary
• Additional Resources

Serving static files

By default, static files are stored in the webroot of your project. The location of the webroot is defined in the project’s
hosting.json file where the default is wwwroot.
"webroot": "wwwroot"

Static files can be stored in any folder under the webroot and accessed with a relative path to that root. For example,
when you create a default Web application project using Visual Studio, there are several folders created within the
webroot folder - css, images, and js. In order to directly access an image in the images subfolder, the URL
would look like the following:
http://<yourApp>/images/<imageFileName>
In order for static files to be served, you must configure the Middleware to add static files to the pipeline. This specific
middleware can be configured by adding a dependency on the Microsoft.AspNetCore.StaticFiles package to your
project and then calling the UseStaticFiles extension method from Startup.Configure as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add static files to the request pipeline.
app.UseStaticFiles();
...

132 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Now, let’s say that you have a project hierarchy where the static files you wish to serve are outside the webroot. For
example,let’s take a simple layout like the following:
• wwwroot
– css
– images
– ...
• MyStaticFiles
– test.png
In order for the user to access test.png, you can configure the static files middleware as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add MyStaticFiles static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStati
RequestPath = new PathString("/StaticFiles")
});
...

At this point, if the user enters an address of http://<yourApp>/StaticFiles/test.png, the test.png


image will be served.

Enabling directory browsing

Directory browsing allows the user of your Web app to see a list of directories and files within a specified directory
(including the root). By default, this functionality is not available such that if the user attempts to display a directory
within an ASP.NET Web app, the browser displays an error. To enable directory browsing for your Web app, call the
UseDirectoryBrowser extension method from Startup.Configure as follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Turn on directory browsing for the current directory.
app.UseDirectoryBrowser();
...

The following figure illustrates the results of browsing to the Web app’s images folder with directory browsing turned
on:

1.4. Fundamentals 133


ASP.NET 5 Documentation, Release

Now, let’s say that you have a project hierarchy where you want the user to be able to browse a directory that is not in
the webroot. For example, let’s take a simple layout like the following:
• wwwroot
– css
– images
– ...
• MyStaticFiles
In order for the user to browse the MyStaticFiles directory, you can configure the static files middleware as
follows:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Add the ability for the user to browse the MyStaticFiles directory.
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStati
RequestPath = new PathString("/StaticFiles")
});
...

At this point, if the user enters an address of http://<yourApp>/StaticFiles, the browser will display the
files in the MyStaticFiles directory.

Serving a default document

Setting a default home page gives site visitors a place to start when visiting your site. Without a default site users
will see a blank page unless they enter a fully qualified URI to a document. In order for your Web app to serve a
default page without the user having to fully qualify the URI, call the UseDefaultFiles extension method from
Startup.Configure as follows.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve the default file, if present.
app.UseDefaultFiles();
app.UseStaticFiles();
...

134 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Note: UseDefaultFiles must be called before UseStaticFiles or it will not serve up the default home page.
You must still call UseStaticFiles. UseDefaultFiles is a URL re-writer that doesn’t actually serve the file.
You must still specify middleware (UseStaticFiles, in this case) to serve the file.

If you call the UseDefaultFiles extension method and the user enters a URI of a folder, the middleware will
search (in order) for one of the following files. If one of these files is found, that file will be used as if the user had
entered the fully qualified URI (although the browser URL will continue to show the URI entered by the user).
• default.htm
• default.html
• index.htm
• index.html
To specify a different default file from the ones listed above, instantiate a DefaultFilesOptions object and set
its DefaultFileNames string list to a list of names appropriate for your app. Then, call one of the overloaded
UseDefaultFiles methods passing it the DefaultFilesOptions object. The following example code re-
moves all of the default files from the DefaultFileNames list and adds mydefault.html as the only default
file for which to search.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve my app-specific default file, if present.
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);
app.UseStaticFiles();
...

Now, if the user browses to a directory in the webroot with a file named mydefault.html, that file will be served
as though the user typed in the fully qualified URI.
But, what if you want to serve a default page from a directory that is outside the webroot directory? You could call both
the UseStaticFiles and UseDefaultFiles methods passing in identical values for each method’s parameters.
However, it’s much more convenient and recommended to call the UseFileServer method, which is covered in
the next section.

Using the UseFileServer method

In addition to the UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser extensions methods,


there is also a single method - UseFileServer - that combines the functionality of all three methods. The following
example code shows some common ways to use this method:
// Enable all static file middleware (serving of static files and default files) EXCEPT directory bro
app.UseFileServer();

// Enables all static file middleware (serving of static files, default files, and directory browsing
app.UseFileServer(enableDirectoryBrowsing: true);

As with the UseStaticFiles, UseDefaultFiles, and UseDirectoryBrowser methods, if you wish to


serve files that exist outside the webroot, you instantiate and configure an “options” object that you pass as a parameter
to UseFileServer. For example, let’s say you have the following directory hierarchy in your Web app:
• wwwroot

1.4. Fundamentals 135


ASP.NET 5 Documentation, Release

– css
– images
– ...
• MyStaticFiles
– test.png
– default.html
Using the hierarchy example above, you might want to enable static files, default files, and browsing for
the MyStaticFiles directory. In the following code snippet, that is accomplished with a single call to
UseFileServer.
// Enable all static file middleware (serving of static files, default files,
// and directory browsing) for the MyStaticFiles directory.
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(@"D:\Source\WebApplication1\src\WebApplication1\MyStaticF
RequestPath = new PathString("/StaticFiles"),
EnableDirectoryBrowsing = true
});

Using the example hierarchy and code snippet from above, here’s what happens if the user browses to various URIs:
• http://<yourApp>/StaticFiles/test.png - The MyStaticFiles/test.png file will be
served to and presented by the browser.
• http://<yourApp>/StaticFiles - Since a default file is present
(MyStaticFiles/default.html), that file will be served. If that file didn’t exist,
the browser would present a list of files in the MyStaticFiles directory (because the
FileServerOptions.EnableDirectoryBrowsing property is set to true).

Working with content types

The ASP.NET static files middleware understands almost 400 known file content types. If the user attempts to reach a
file of an unknown file type, the static file middleware will not attempt to serve the file.
Let’s take the following directory/file hierarchy example to illustrate:
• wwwroot
– css
– images

* test.image
– ...
Using this hierarchy, you could enable static file serving and directory browsing with the following:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve static files and allow directory browsing.
app.UseDirectoryBrowser();
app.UseStaticFiles();

136 Chapter 1. Topics


ASP.NET 5 Documentation, Release

If the user browses to http://<yourApp>/images, a directory listing will be displayed by the browser
that includes the test.image file. However, if the user clicks on that file, they will see a 404 error -
even though the file obviously exists. In order to allow the serving of unknown file types, you could set the
StaticFileOptions.ServeUnknownFileTypes property to true and specify a default content type via
StaticFileOptions.DefaultContentType. (Refer to this list of common MIME content types.)
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...
// Serve static files and allow directory browsing.
app.UseDirectoryBrowser();
app.UseStaticFiles(new StaticFileOptions
{
ServeUnknownFileTypes = true,
DefaultContentType = "image/png"
});

At this point, if the user browses to a file whose content type is unknown, the browser will treat it as an image and
render it accordingly.
So far, you’ve seen how to specify a default content type for any file type that ASP.NET doesn’t recog-
nize. However, what if you have multiple file types that are unknown to ASP.NET? That’s where the
FileExtensionContentTypeProvider class comes in.
The FileExtensionContentTypeProvider class contains an internal collection that
maps file extensions to MIME content types. To specify custom content types, simply in-
stantiate a FileExtensionContentTypeProvider object and add a mapping to the
FileExtensionContentTypeProvider.Mappings dictionary for each needed file extension/content
type. In the following example, the code adds a mapping of the file extension .myapp to the MIME content type
application/x-msdownload.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
...

// Allow directory browsing.


app.UseDirectoryBrowser();

// Set up custom content types - associating file extension to MIME type


var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".myapp", "application/x-msdownload");

// Serve static files.


app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });

...

Now, if the user attempts to browse to any file with an extension of .myapp, the user will be prompted to download
the file (or it will happen automatically depending on the browser).

IIS Considerations

ASP.NET Core applications hosted in IIS use the HTTP platform handler to forward all requests to the application
including requests for static files. The IIS static file handler is not used because it won’t get a chance to handle the
request before it is handled by the HTTP platform handler.

1.4. Fundamentals 137


ASP.NET 5 Documentation, Release

Best practices

This section includes a list of best practices for working with static files:
• Code files (including C# and Razor files) should be placed outside of the app project’s webroot. This creates a
clean separation between your app’s static (non-compilable) content and source code.

Summary

In this article, you learned how the static files middleware component in ASP.NET Core allows you to serve static files,
enable directory browsing, and serve default files. You also saw how to work with content types that ASP.NET doesn’t
recognize. Finally, the article explained some IIS considerations and presented some best practices for working with
static files.

Additional Resources

• Middleware

1.4.4 Routing

By Steve Smith
Routing middleware is used to map requests to route handlers. Routes are configured when the application starts up,
and can extract values from the URL that will be passed as arguments to route handlers. Routing functionality is also
responsible for generating links that correspond to routes in ASP.NET apps.

Sections
• Routing Middleware
• Configuring Routing
• Template Routes
• Route Builder Extensions
• Link Generation
• Recommendations

View or download sample code

Routing Middleware

The routing middleware uses routes to map requests to an IRouter instance. The IRouter in-
stance chooses whether or not to handle the request, and how. The request is considered handled if its
RouteContext.IsHandled property is set to true. If no route handler is found for a request, then the mid-
dleware calls next (and the next middleware in the request pipeline is invoked).
To use routing, add it to the dependencies in project.json:
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Routing": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final"

138 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Add routing to ConfigureServices in Startup.cs:


public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}

Configuring Routing

Routing is enabled in the Configure method in the Startup class. Create an instance of RouteBuilder. You
can optionally set the ServiceProvider and/or DefaultHandler properties, in order to make them available as you build
routes.
public void Configure(IApplicationBuilder app,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
app.UseIISPlatformHandler();

var routeBuilder = new RouteBuilder();


routeBuilder.ServiceProvider = app.ApplicationServices;

routeBuilder.Routes.Add(new TemplateRoute(
new HelloRouter(),
"hello/{name:alpha}",
app.ApplicationServices.GetService<IInlineConstraintResolver>()));

app.UseRouter(routeBuilder.Build());

You can see on the last line above how ApplicationServices is used to access the
IInlineConstraintResolver dependency; if this were done from a RouteBuilder extension method,
access to the services would be done through the ServiceProvider property.
Once you’ve finished adding routes to the RouteBuilder instance, call UseRouter and pass it the result of the
RouteBuilder.Build method.

Tip: If you are only configuring a single route, you can simply call app.UseRouter and pass in the IRouter
instance you wish to use, bypassing the need to use a RouteBuilder.

The route configured above will only match requests of the form “hello/{name}” where name is constrained to be
alphabetical. Requests that match this will be handled by a custom IRouter implementation, HelloRouter.
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Routing;

namespace RoutingSample
{
public class HelloRouter : IRouter
{
public async Task RouteAsync(RouteContext context)
{
var name = context.RouteData.Values["name"] as string;
if (String.IsNullOrEmpty(name))
{
return;

1.4. Fundamentals 139


ASP.NET 5 Documentation, Release

}
await context.HttpContext.Response.WriteAsync($"Hi {name}!");
context.IsHandled = true;
}

public VirtualPathData GetVirtualPath(VirtualPathContext context)


{
return null;
}
}
}

HelloRouter checks to see if RouteData includes a value for the key name. If not, it immediately returns without
handling the request. Otherwise, the request is handled (by writing out “Hi {name}!”) and the RouteContext
is updated to note that the request was handled. This prevents additional routes from handling the request. The
GetVirtualPath method is used for link generation.

Note: Remember, it’s possible for a particular route template to match a given request, but the associated route
handler can still reject it, allowing a different route to handle the request.)

This route was configured to use an inline constraint, signified by the :alpha in the name route value. This con-
straint limits which requests this route will handle, in this case to alphabetical values for name. Thus, a request for
“/hello/steve” will be handled, but a request to “/hello/123” will not (instead, the request will pass through to the
“Hello World!” request delegate).

Template Routes

The most common way to define routes is using TemplateRoute and route template strings. When a
TemplateRoute matches, it calls its target IRouter handler. In a typical MVC app, you might use a default
template route with a string like this one:

This route template would be handled by the MvcRouteHandler IRouter instance. Tokens within curly braces
({ }) define route value parameters which will be bound if the route is matched. You can define more than
one route value parameter in a route segment, but they must be separated by a literal value. For example
{controller=Home}{action=Index} would not be a valid route, since there is no literal value between
{controller} and {action}. These route value parameters must have a name, and may have additional at-
tributes specified.
You can use the * character as a prefix to a route value name to bind to the rest of the URI. For example,
blog/{*slug} would match any URI that started with /blog/ and had any value following it (which would
be assigned to the slug route value).
Route value parameters may have default values, designated by specifying the default after the parameter name,
separated by an =. For example, controller=Home would define Home as the default value for controller.
The default value is used if no value is present in the URL for the parameter. In addition to default values, route
parameters may be optional (specified by appending a ? to the end of the parameter name, as in id?). The difference
between optional and “has default” is that a route parameter with a default value always produces a value; an optional
parameter may not. Route parameters may also have constraints, which further restrict which routes the template will
match.
The following table demonstrates some route template and their expected behavior.

140 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Table 1.2: Route Template Values


Route Template Example Notes
Matching URL
hello /hello Will only match the single path ‘/hello’
{Page=Home} / Will match and set Page to Home.
{Page=Home} /Contact Will match and set Page to Contact
{con- /Products/List Will map to Products controller and List method; Since id
troller}/{action}/{id?} was not supplied in the URL, it’s ignored.
{con- /Prod- Will map to Products controller and Details method, with
troller}/{action}/{id?} ucts/Details/123 id set to 123.
{con- / Will map to Home controller and Index method; id is ignored.
troller=Home}/{action=Index}/{id?}

Route Constraints

Adding a colon : after the name allows additional inline constraints to be set on a route value parameter. Constraints
with types always use the invariant culture - they assume the URL is non-localizable. Route constraints limit which
URLs will match a route - URLs that do not match the constraint are ignored by the route.

Table 1.3: Inline Route Constraints


constraint Example Example Match Notes
int {id:int} 123 Matches any integer
bool {active:bool} true Matches true or false
datetime {dob:datetime} 2016-01-01 Matches a valid DateTime value (in the
invariant culture - see options)
decimal {price:decimal}
49.99 Matches a valid decimal value
double {price:double}
4.234 Matches a valid double value
float {price:float}3.14 Matches a valid float value
guid {id:guid} 7342570B-44E7-471C- Matches a valid Guid value
A267-947DD2A35BF9
long {ticks:long} 123456789 Matches a valid long value
{user-
minlength(value) steve String must be at least 5 characters long.
name:minlength(5)}
{file-
maxlength(value) somefile String must be no more than 8 characters long.
name:maxlength(8)}
{file-
length(min,max) Somefile.txt String must be at least 8 and no more than 16
name:length(4,16)} characters long.
min(value) {age:min(18)} 19 Value must be at least 18.
max(value) {age:max(120)} 91 Value must be no more than 120.
{age:range(18,120)}91
range(min,max) Value must be at least 18 but no more than 120.
alpha {name:alpha} Steve String must consist of alphabetical characters.
{ssn:regex(d{3}- 123-45-6789
regex(expression) String must match the provided regular
d{2}-d{4})} expression.
required {name:required} Steve Used to enforce that a non-parameter value is
present during during URL generation.
Inline constraints must match one of the above options, or an exception will be thrown.

Tip: To constrain a parameter to a known set of possible values, you can use a regex:
{action:regex(list|get|create)}. This would only match the action route value to list, get, or
create. If passed into the constraints dictionary, the string “list|get|create” would be equivalent. Constraints that are

1.4. Fundamentals 141


ASP.NET 5 Documentation, Release

passed in the constraints dictionary (not inline within a template) that don’t match one of the known constraints are
also treated as regular expressions.

Warning: Avoid using constraints for validation, because doing so means that invalid input will result in a 404
(Not Found) instead of a 400 with an appropriate error message. Route constraints should be used to disambiguate
between routes, not validate the inputs for a particular route.

Constraints can be chained. You can specify that a route value is of a certain type and also must fall within a spec-
ified range, for example: {age:int:range(1,120)}. Numeric constraints like min, max, and range will
automatically convert the value to long before being applied unless another numeric type is specified.
Route templates must be unambiguous, or they will be ignored. For example, {id?}/{foo} is ambiguous, because
it’s not clear which route value would be bound to a request for “/bar”. Similarly, {*everything}/{plusone}
would be ambiguous, because the first route parameter would match everything from that part of the request on, so it’s
not clear what the plusone parameter would match.

Note: There is a special case route for filenames, such that you can define a route value like
files/{filename}.{ext?}. When both filename and ext exist, both values will be populated. How-
ever, if only filename exists in the URL, the trailing period . is also optional. Thus, these would both match:
/files/foo.txt and /files/foo.

Tip: Enable Logging to see how the built in routing implementations, such as TemplateRoute, match requests.

Route Builder Extensions

Several extension methods on RouteBuilder are available for convenience. The most common of these is
MapRoute, which allows the specification of a route given a name and template, and optionally default values,
constraints, and/or data tokens. When using these extensions, you must have specified the DefaultHandler
and ServiceProvider properties of the RouteBuilder instance to which you’re adding the route. These
MapRoute extensions add new TemplateRoute instances to the RouteBuilder that each target the IRouter
configured as the DefaultHandler.

Note: MapRoute doesn’t take an IRouter parameter - it only adds routes that will be handled by the
DefaultHandler. Since the default handler is an IRouter, it may decide not to handle the request. For ex-
ample, MVC is typically configured as a default handler that only handles requests that match an available controller
action.

The following DelegateRouter accepts any values and displays them:


using System.Threading.Tasks;
using Microsoft.AspNet.Routing;

namespace RoutingSample
{
public class DelegateRouter : IRouter
{
public delegate Task RoutedDelegate(RouteContext context);

private readonly RoutedDelegate _appFunc;

public DelegateRouter(RoutedDelegate appFunc)


{
_appFunc = appFunc;

142 Chapter 1. Topics


ASP.NET 5 Documentation, Release

public async Task RouteAsync(RouteContext context)


{
await _appFunc(context);
context.IsHandled = true;
}

public VirtualPathData GetVirtualPath(VirtualPathContext context)


{
context.IsBound = true;
return null;
}
}
}

You configure this IRouter implementation as the DefaultHandler for a RouteBuilder in the Configure
method in Startup:
var routeBuilder = new RouteBuilder();
routeBuilder.ServiceProvider = app.ApplicationServices;

routeBuilder.Routes.Add(new TemplateRoute(
new HelloRouter(),
"hello/{name:alpha}",
app.ApplicationServices.GetService<IInlineConstraintResolver>()));

var endpoint1 = new DelegateRouter(async (context) =>


await context
.HttpContext
.Response
.WriteAsync("Hello world! Route Values: " +
string.Join("", context.RouteData.Values)));

routeBuilder.DefaultHandler = endpoint1;

routeBuilder.MapRoute(
"Track Package Route",
"package/{operation:regex(track|create|detonate)}/{id:int}");

app.UseRouter(routeBuilder.Build());

Data Tokens

Data tokens represent data that is carried along if the route matches. They’re implemented as a property bag for
developer-specified data. You can use data tokens to store data you want to associate with a route, when you don’t
want the semantics of defaults. Data tokens have no impact on the behavior of the route, while defaults do. Data
tokens can also be any arbitrary types, while defaults really need to be things that can be converted to/from strings.

Link Generation

Routing is also used to generate URLs based on route definitions. This is used by helpers to generate links to known
actions on MVC controllers, but can also be used independent of MVC. Given a set of route values, and optionally a
route name, you can produce a VirtualPathContext object. Using the VirtualPathContext object along

1.4. Fundamentals 143


ASP.NET 5 Documentation, Release

with a RouteCollection, you can generate a VirtualPath. IRouter implementations participate in link
generation through the GetVirtualPath method.

Tip: Learn more about UrlHelper and Routing to Controller Actions.

The example below shows how to generate a link to a route given a dictionary of route values and a
RouteCollection.
1 routeBuilder.MapRoute(
2 "Track Package Route",
3 "package/{operation:regex(track|create|detonate)}/{id:int}");
4

5 app.UseRouter(routeBuilder.Build());
6

7 // demonstrate link generation


8 var trackingRouteCollection = new RouteCollection();
9 trackingRouteCollection.Add(routeBuilder.Routes[1]); // "Track Package Route"
10

11 app.Run(async (context) =>


12 {
13 var dictionary = new RouteValueDictionary
14 {
15 {"operation","create" },
16 {"id",123}
17 };
18

19 var vpc = new VirtualPathContext(context,


20 null, dictionary, "Track Package Route");
21

22 context.Response.ContentType = "text/html";
23 await context.Response.WriteAsync("Menu<hr/>");
24 await context.Response.WriteAsync(@"<a href='" +
25 trackingRouteCollection.GetVirtualPath(vpc).VirtualPath +
26 "'>Create Package 123</a><br/>");

The VirtualPath generated at the end of the sample above is /package/create/123.


The second parameter to the VirtualPathContext constructor is a collection of ambient values. Ambient values
provide convenience by limiting the number of values a developer must specify within a certain request context. The
current route values of the current request are considered ambient values for link generation. For example, in an MVC
application if you are in the About action of the HomeController, you don’t need to specify the controller route value
to link to the Index action (the ambient value of Home will be used).
Ambient values that don’t match a parameter are ignored, and ambient values are also ignored when an explicitly-
provided value overrides it, going from left to right in the URL.
Values that are explicitly provided but which don’t match anything are added to the query string.

Table 1.4: Generating Links


Matched Route Ambient Values Explicit Values Result
controller=”Home”
{controller}/{action}/{id?} action=”About” /Home/About
controller=”Home”
{controller}/{action}/{id?} con- /Order/About
troller=”Order”,action=”About”
con-
{controller}/{action}/{id?} action=”About” /Home/About
troller=”Home”,color=”Red”
controller=”Home”
{controller}/{action}/{id?} ac- /Home/About?color=Red
tion=”About”,color=”Red”

144 Chapter 1. Topics


ASP.NET 5 Documentation, Release

If a route has a default value that doesn’t match a parameter and that value is explicitly provided, it must match the
default value. For example:
routes.MapRoute("blog_route", "blog/{*slug}",
defaults: new { controller = "Blog", action = "ReadPost" });

Link generation would only generate a link for this route when the matching values for controller and action are
provided.

Recommendations

Routing is a powerful feature that is built into the default ASP.NET MVC project template such that most apps will
be able to leverage it without having to customize its behavior. This is by design; customizing routing behavior is an
advanced development approach. Keep in mind the following recommendations with regard to routing:
• Most apps shouldn’t need custom routes. The default route will work in most cases.
• Attribute routes should be used for all APIs.
• Attribute routes are recommended for when you need complete control over your app’s URLs.
• Conventional routing is recommended for when all of your controllers/actions fit a uniform URL convention.
• Don’t use custom routes unless you understand them well and are sure you need them.
• Routes can be tricky to test and debug.
• Routes should not be used as a means of securing your controllers or their action methods.
• Avoid building or changing route collections at runtime.

1.4.5 Diagnostics

Steve Smith
ASP.NET Core includes a number of new features that can assist with diagnosing problems.

Sections
• The developer error page
• The welcome page
• Glimpse
• Logging

You can add a runtime info page by simply calling an extension method in the Configure method of Startup.cs:
if (env.IsDevelopment())
{
app.UseRuntimeInfoPage(); // default path is /runtimeinfo
}

Once this is added to your application, you can browse to the specified path (/runtimeinfo) to see information
about the runtime that is being used and the packages that are included in the application, as shown below:

1.4. Fundamentals 145


ASP.NET 5 Documentation, Release

The path for this page can be optionally specified in the call to UseRuntimeInfoPage(). It accepts a Runtime-
InfoPageOptions instance as a parameter, which has a Path property. For example, to specify a path of /info you
would call UseRuntimeInfoPage() as shown here:
if (env.IsDevelopment())
{
app.UseRuntimeInfoPage("/info");
}

Diagnostic information should not be exposed in production. The code above prevents diagnostics outside the devel-
opment environment.

Note: Remember that the Configure() method in Startup.cs is defining the pipeline that will be used
by all requests to your application, which means the order is important. If for example you move the call to
UseRuntimeInfoPage() after the call to app.Run() in the examples shown here, it will never be called because
app.Run() will handle the request before it reaches the call to UseRuntimeInfoPage.

The developer error page

You can view the details of unhandled exceptions by specifying a developer error page. This topic is described in Error
Handling.

The welcome page

Another extension method you may find useful, especially when you’re first spinning up a new ASP.NET Core appli-
cation, is the UseWelcomePage() method. Add it to Configure() like so:
app.UseWelcomePage();

Once included, this will handle all requests (by default) with a cool hello world page that uses embedded images and
fonts to display a rich view, as shown here:

146 Chapter 1. Topics


ASP.NET 5 Documentation, Release

You can optionally configure the welcome page to only respond to certain paths. The code shown below will configure
the page to only be displayed for the /welcome path (other paths will be ignored, and will fall through to other
handlers):
app.UseWelcomePage("/welcome");

Glimpse

Glimpse is a plug-in that provides a tremendous amount of insight into your ASP.NET Core application, directly from
the browser. Glimpse can be added to your in app in just a few simple steps:
• Add a dependency on the “Glimpse” package in project.json
• Call services.AddGlimpse in ConfigureServices
• Call app.UseGlimpse in Configure
Run your app on localhost, and you should see Glimpse information bar at the bottom of the browser window. View a
walkthrough of setting up Glimpse for ASP.NET Core.

Logging

ASP.NET Core includes a great deal of built-in logging that can assist with diagnosing many app issues. In many
cases, just enabling logging is sufficient to provide the diagnostic information developers need to identify problems
with their app. Logging is enabled and configured in your app’s Startup class.
Learn more about configuring logging in your ASP.NET Core app.

Note: Application Insights can provide production diagnostic information in a cloud-based, searchable format.

1.4. Fundamentals 147


ASP.NET 5 Documentation, Release

1.4.6 Error Handling

By Steve Smith
When errors occur in your ASP.NET app, you can handle them in a variety of ways, as described in this article.

Sections
• Configuring an Exception Handling Page
• Using the Developer Exception Page
• Configuring Status Code Pages
• Limitations of Exception Handling During Client-Server Interaction
• Server Exception Handling
• Startup Exception Handling
• ASP.NET MVC Error Handling

View or download sample code

Configuring an Exception Handling Page

You configure the pipeline for each request in the Startup class’s Configure() method (learn more about Appli-
cation Startup). You can add a simple exception page, meant only for use during development, very easily. All that’s
required is to add a dependency on Microsoft.AspNet.Diagnostics to the project and then add one line to
Configure() in Startup.cs:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env)
{
app.UseIISPlatformHandler();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

The above code includes a check to ensure the environment is development before adding the call to
UseDeveloperExceptionPage. This is a good practice, since you typically do not want to share detailed excep-
tion information about your application publicly while it is in production. Learn more about configuring environments.
The sample application includes a simple mechanism for creating an exception:
ic static void HomePage(IApplicationBuilder app)

app.Run(async (context) =>


{
if (context.Request.Query.ContainsKey("throw"))
{

If a request includes a non-empty querystring parameter for the variable throw (e.g. a path of /?throw=true), an
exception will be thrown. If the environment is set to Development, the developer exception page is displayed:

148 Chapter 1. Topics


ASP.NET 5 Documentation, Release

When not in development, it’s a good idea to configure an exception handler path using the
UseExceptionHandler middleware:
app.UseExceptionHandler("/Error");

Using the Developer Exception Page

The developer exception page displays useful diagnostics information when an unhandled exception occurs within the
web processing pipeline. The page includes several tabs with information about the exception that was triggered and
the request that was made. The first tab includes a stack trace:

1.4. Fundamentals 149


ASP.NET 5 Documentation, Release

The next tab shows the query string parameters, if any:

In this case, you can see the value of the throw parameter that was passed to this request. This request didn’t have
any cookies, but if it did, they would appear on the Cookies tab. You can see the headers that were passed in the last
tab:

150 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Configuring Status Code Pages

By default, your app will not provide a rich status code page for HTTP status codes such as 500 (Internal Server Error)
or 404 (Not Found). You can configure the StatusCodePagesMiddleware adding this line to the Configure
method:
app.UseStatusCodePages();

By default, this middleware adds very simple, text-only handlers for common status codes. For example, the following
is the result of a 404 Not Found status code:

1.4. Fundamentals 151


ASP.NET 5 Documentation, Release

The middleware supports several different extension methods. You can pass it a custom lamba expression:
app.UseStatusCodePages(context =>
context.HttpContext.Response.SendAsync("Handler, status code: " +
context.HttpContext.Response.StatusCode, "text/plain"));

Alternately, you can simply pass it a content type and a format string:
app.UseStatusCodePages("text/plain", "Response, status code: {0}");

The middleware can handle redirects (with either relative or absolute URL paths), passing the status code as part of
the URL:
app.UseStatusCodePagesWithRedirects("~/errors/{0}");

In the above case, the client browser will see a 302 / Found status and will redirect to the URL provided.
Alternately, the middleware can re-execute the request from a new path format string:
app.UseStatusCodePagesWithReExecute("/errors/{0}");

The UseStatusCodePagesWithReExecute method will still return the original status code to the browser, but
will also execute the handler given at the path specified.
If you need to disable status code pages for certain requests, you can do so using the following code:
var statusCodePagesFeature = context.Features.Get<IStatusCodePagesFeature>();
if (statusCodePagesFeature != null)
{
statusCodePagesFeature.Enabled = false;
}

152 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Limitations of Exception Handling During Client-Server Interaction

Web apps have certain limitations to their exception handling capabilities because of the nature of disconnected HTTP
requests and responses. Keep these in mind as you design your app’s exception handling behavior.
1. Once the headers for a response have been sent, you cannot change the response’s status code, nor can any
exception pages or handlers run. The response must be completed or the connection aborted.
2. If the client disconnects mid-response, you cannot send them the rest of the content of that response.
3. There is always the possibility of an exception occuring one layer below your exception handling layer.
4. Don’t forget, exception handling pages can have exceptions, too. It’s often a good idea for production error
pages to consist of purely static content.
Following the above recommendations will help ensure your app remains responsive and is able to gracefully handle
exceptions that may occur.

Server Exception Handling

In addition to the exception handling logic in your app, the server hosting your app will perform some exception
handling. If the server catches an exception before the headers have been sent it will send a 500 Internal Server
Error response with no body. If it catches an exception after the headers have been sent it must close the connection.
Requests that are not handled by your app will be handled by the server, and any exception that occurs will be handled
by the server’s exception handling. Any custom error pages or exception handling middleware or filters you have
configured for your app will not affect this behavior.

Startup Exception Handling

One of the trickiest places to handle exceptions in your app is during its startup. Only the hosting layer can handle
exceptions that take place during app startup. Exceptions that occur in your app’s startup can also impact server
behavior. For example, to enable SSL in Kestrel, one must configure the server with app.UseKestrelHttps().
If an exception happens before this line in Startup, then by default hosting will catch the exception, start the server,
and display an error page on the non-SSL port. If an exception happens after that line executes, then the error page
will be served over HTTPS instead.

ASP.NET MVC Error Handling

MVC apps have some additional options when it comes to handling errors, such as configuring exception filters and
performing model validation.

Exception Filters

Exception filters can be configured globally or on a per-controller or per-action basis in an MVC app. These filters
handle any unhandled exception that occurs during the execution of a controller action or another filter, and are not
called otherwise. Exception filters are detailed in filters.

Tip: Exception filters are good for trapping exceptions that occur within MVC actions, but they’re not as flexible as
error handling middleware. Prefer middleware for the general case, and use filters only where you need to do error
handling differently based on which MVC action was chosen.

1.4. Fundamentals 153


ASP.NET 5 Documentation, Release

Handling Model State Errors

Model validation occurs prior to each controller action being invoked, and it is the action method’s responsibility to
inspect ModelState.IsValid and react appropriately. In many cases, the appropriate reaction is to return some
kind of error response, ideally detailing the reason why model validation failed.
Some apps will choose to follow a standard convention for dealing with model validation errors, in which case a filter
may be an appropriate place to implement such a policy. You should test how your actions behave with valid and
invalid model states (learn more about testing controller logic).

1.4.7 Globalization and localization

Rick Anderson, Damien Bowden, Bart Calixto, Nadeem Afana


Creating a multilingual website with ASP.NET Core will allow your site to reach a wider audience. ASP.NET Core
provides services and middleware for localizing into different languages and cultures.
Internationalization involves Globalization and Localization. Globalization is the process of designing apps that sup-
port different cultures. Globalization adds support for input, display, and output of a defined set of language scripts
that relate to specific geographic areas.
Localization is the process of adapting a globalized app, which you have already processed for localizability, to
a particular culture/locale. For more information see Globalization and localization terms near the end of this
document.
App localization involves the following:
1. Make the app’s content localizable
2. Provide localized resources for the languages and cultures you support
3. Implement a strategy to select the language/culture for each request

Sections:
• Make the app’s content localizable
• View localization
• DataAnnotations localization
• Provide localized resources for the languages and cultures you support
• Working with resource files
• Implement a strategy to select the language/culture for each request
• Resource file naming
• Globalization and localization terms
• Additional Resources

Make the app’s content localizable

Introduced in ASP.NET Core, IStringLocalizer and IStringLocalizer<T> were architected to improve productivity
when developing localized apps. IStringLocalizer uses the ResourceManager and ResourceReader to provide
culture-specific resources at run time. The simple interface has an indexer and an IEnumerable for returning
localized strings. IStringLocalizer doesn’t require you to store the default language strings in a resource file.
You can develop an app targeted for localization and not need to create resource files early in development. The code
below shows how to wrap the string “About Title” for localization.

154 Chapter 1. Topics


ASP.NET 5 Documentation, Release

using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Localization;

namespace Localization.StarterWeb.Controllers
{
[Route("api/[controller]")]
public class AboutController : Controller
{
private readonly IStringLocalizer<AboutController> _localizer;

public AboutController(IStringLocalizer<AboutController> localizer)


{
_localizer = localizer;
}

[HttpGet]
public string Get()
{
return _localizer["About Title"];
}
}
}

In the code above, the IStringLocalizer<T> implementation comes from Dependency Injection. I’ll show
how the IStringLocalizer service gets added in the Configuring localization section. If the localized value of
“About Title” is not found, then the indexer key is returned, that is, the string “About Title”. You can leave the default
language literal strings in the app and wrap them in the localizer, so that you can focus on developing the app. You
develop your app with your default language and prepare it for the localization step without first creating a default
resource file. Alternatively, you can use the traditional approach and provide a key to retrieve the default language
string. For many developers the new workflow of not having a default language .resx file and simply wrapping the
string literals can reduce the overhead of localizing an app. Other developers will prefer the traditional work flow as it
can make it easier to work with longer string literals and make it easier to update localized strings.
Use the IHtmlLocalizer<T> implementation for resources that contain HTML. IHtmlLocalizer HTML encodes
arguments that are formatted in the resource string, but not the resource string. In the sample highlighted below, only
the value of name parameter is HTML encoded.
using System;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Localization;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Localization;

namespace Localization.StarterWeb.Controllers
{
public class BookController : Controller
{
private readonly IHtmlLocalizer<BookController> _localizer;

public BookController(IHtmlLocalizer<BookController> localizer)


{
_localizer = localizer;
}

public IActionResult Hello(string name)


{
ViewData["Message"] = _localizer["<b>Hello</b><i> {0}</i>", name];

1.4. Fundamentals 155


ASP.NET 5 Documentation, Release

return View();
}

Note You generally want to only localize text and not HTML.
At the lowest level, you can get IStringLocalizerFactory out of Dependency Injection:
public class TestController : Controller
{
private readonly IStringLocalizer _localizer;
private readonly IStringLocalizer _localizer2;

public TestController(IStringLocalizerFactory factory)


{
_localizer = factory.Create(typeof(SharedResource));
_localizer2 = factory.Create("SharedResource", location: null);
}

public IActionResult About()


{
ViewData["Message"] = _localizer["Your application description page."]
+ " loc 2: " + _localizer2["Your application description page."];

return View();
}

The code above demonstrates each of the two factory create methods.
You can partition your localized strings by controller, area, or have just one container. In the sample app, a dummy
class named SharedResource is used for shared resources.
// Dummy class to group shared resources

namespace Localization.StarterWeb
{
public class SharedResource
{
}
}

Some developers use the Startup class to contain global or shared strings. In the sample below, the
InfoController and the SharedResource localizers are used:
public class InfoController : Controller
{
private readonly IStringLocalizer<InfoController> _localizer;
private readonly IStringLocalizer<SharedResource> _sharedLocalizer;

public InfoController(IStringLocalizer<InfoController> localizer,


IStringLocalizer<SharedResource> sharedLocalizer)
{
_localizer = localizer;
_sharedLocalizer = sharedLocalizer;
}

public string TestLoc()


{
string msg = "Shared resx: " + _sharedLocalizer["Hello!"] +
" Info resx " + _localizer["Hello!"];

156 Chapter 1. Topics


ASP.NET 5 Documentation, Release

return msg;
}

View localization

The IViewLocalizer service provides localized strings for a view. The ViewLocalizer class implements this interface
and finds the resource location from the view file path. The following code shows how to use the default implementa-
tion of IViewLocalizer:
@using Microsoft.AspNet.Mvc.Localization

@inject IViewLocalizer Localizer

@{
ViewData["Title"] = Localizer["About"];
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p>@Localizer["Use this area to provide additional information."]</p>

The default implementation of IViewLocalizer finds the resource file based on the view’s file name. There is
no option to use a global shared resource file. ViewLocalizer implements the localizer using IHtmlLocalizer, so
Razor doesn’t HTML encode the localized string. You can parameterize resource strings and IViewLocalizer
will HTML encode the parameters, but not the resource string. Consider the following Razor markup:
@Localizer["<i>Hello</i> <b>{0}!</b>", UserManager.GetUserName(User)]

A French resource file could contain the following:


Key Value
<i>Hello</i> <b>{0}!</b> <i>Bonjour</i> <b>{0}!</b>
The rendered view would contain the HTML markup from the resource file.
Note You generally want to only localize text and not HTML.
To use a shared resource file in a view, inject IHtmlLocalizer<T>:
@using Microsoft.AspNet.Mvc.Localization
@using Localization.StarterWeb.Services

@inject IViewLocalizer Localizer


@inject IHtmlLocalizer<SharedResource> SharedLocalizer

@{
ViewData["Title"] = Localizer["About"];
}
<h2>@ViewData["Title"].</h2>

<h1>@SharedLocalizer["Hello!"]</h1>

DataAnnotations localization

DataAnnotations error messages are localized with IStringLocalizer<T>. Using the option ResourcesPath =
"Resources", the error messages in RegisterViewModel can be stored in either of the following paths:
• Resources/ViewModels.Account.RegisterViewModel.fr.resx

1.4. Fundamentals 157


ASP.NET 5 Documentation, Release

• Resources/ViewModels/Account/RegisterViewModel.fr.resx
public class RegisterViewModel
{
[Required(ErrorMessage = "The Email field is required.")]
[EmailAddress(ErrorMessage = "The Email field is not a valid e-mail address.")]
[Display(Name = "Email")]
public string Email { get; set; }

[Required(ErrorMessage = "The Password field is required.")]


[StringLength(8, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength =
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}

The runtime doesn’t look up localized strings for non-validation attributes. In the code above, “Email” (from
[Display(Name = "Email")]) will not be localized.

Provide localized resources for the languages and cultures you support

SupportedCultures and SupportedUICultures

ASP.NET Core allows you to specify two culture values, SupportedCultures and SupportedUICultures.
The CultureInfo object for SupportedCultures determines the results of culture-dependent functions, such as
date, time, number, and currency formatting. SupportedCultures also determines the sorting order of text,
casing conventions, and string comparisons. See CultureInfo.CurrentCulture for more info on how the server gets
the Culture. The SupportedUICultures determines which translates strings (from .resx files) are looked up
by the ResourceManager. The ResourceManager simply looks up culture-specific strings that is determined
by CurrentUICulture. Every thread in .NET has CurrentCulture and CurrentUICulture objects.
ASP.NET Core inspects these values when rendering culture-dependent functions. For example, if the current thread’s
culture is set to “en-US” (English, United States), DateTime.Now.ToLongDateString() displays “Thursday,
February 18, 2016”, but if CurrentCulture is set to “es-ES” (Spanish, Spain) the output will be “jueves, 18 de
febrero de 2016”.

Note: Currently, resource files are not read when the project is run from Visual Studio. See this issue for more
information. Until the issue with Visual Studio is addressed, you can test the project by running it from the command
line.

Working with resource files

A resource file is a useful mechanism for separating localizable strings from code. Translated strings for the non-
default language are isolated .resx resource files. For example, you might want to create Spanish resource file named
Welcome.es.resx containing translated strings. “es” is the language code for Spanish. To create this resource file in
Visual Studio:
1. In Solution Explorer, right click on the folder which will contain the resource file > Add > New Item.

158 Chapter 1. Topics


ASP.NET 5 Documentation, Release

2. In the Search installed templates box, enter “resource” and name the file.

1.4. Fundamentals 159


ASP.NET 5 Documentation, Release

3. Enter the key value (native string) in the Name column and the translated string in the Value column.

Visual Studio shows the Welcome.es.resx file.

160 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Generating resource files with Visual Studio

If you create a resource file in Visual Studio without a culture in the file name (for example, Welcome.resx), Visual
Studio will create a C# class with a property for each string. That’s usually not what you want with ASP.NET Core;
you typically don’t have a default .resx resource file (A .resx file without the culture name). We suggest you create the
.resx file with a culture name (for example Welcome.fr.resx). When you create a .resx file with a culture name, Visual
Studio will not generate the class file. We anticipate that many developers will not create a default language resource
file.

Adding Other Cultures

Each language and culture combination (other than the default language) requires a unique resource file. You can
create resource files for different cultures and locales by creating new resource files in which the ISO language codes
are part of the file name (for example, en-us, fr-ca, and en-gb). These ISO codes are placed between the file name and
the .resx file name extension, as in Welcome.es-MX.resx (Spanish/Mexico). To specify a culturally neutral language,
you would eliminate the country code, such as Welcome.fr.resx for the French language.

Implement a strategy to select the language/culture for each request

Configuring localization

Localization is configured in the ConfigureServices method:

1.4. Fundamentals 161


ASP.NET 5 Documentation, Release

public void ConfigureServices(IServiceCollection services)


{

services.AddLocalization(options => options.ResourcesPath = "Resources");

services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();

• AddLocalization Adds the localization services to the services container. The code above also sets the
resources path to “Resources”.
• AddViewLocalization Adds support for localized view files. In this sample view localization is based on
the view file suffix. For example “fr” in the Index.fr.cshtml file.
• AddDataAnnotationsLocalization Adds support for localized DataAnnotations validation mes-
sages through IStringLocalizer abstractions.

Localization middleware

The current culture on a request is set in the localization Middleware. The localization middleware is enabled in the
Configure method of Startup.cs file.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactor

var supportedCultures = new[]


{
new CultureInfo("en-US"),
new CultureInfo("en-AU"),
new CultureInfo("en-GB"),
new CultureInfo("en"),
new CultureInfo("es-ES"),
new CultureInfo("es-MX"),
new CultureInfo("es"),
new CultureInfo("fr-FR"),
new CultureInfo("fr"),
};

app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});

// Remaining code omitted for brevity.

UseRequestLocalization initializes a RequestLocalizationMiddleware object. On every request the list of Request-


CultureProvider in the RequestLocalizationOptions is enumerated and the first non-null provider is used. The default
providers come from the RequestLocalizationOptions class:
1. QueryStringRequestCultureProvider
2. CookieRequestCultureProvider
3. AcceptLanguageHeaderRequestCultureProvider

162 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The default list goes from most specific to least specific. Later in the article I’ll show how you can change the order
and even add a custom localization provider. If there are no non-null providers, the DefaultRequestCulture is
used.

QueryStringRequestCultureProvider

Some apps will use a query string to set the culture and UI culture. For apps that use the cookie or Accept-Language
header approach, adding a query string to the URL is useful for debugging and testing code. Unless you change
the RequestCultureProvider list, a query string will always win as the localization provider. You pass the
query string parameters culture and ui-culture. The following example sets the specific culture (language and
region) to Spanish/Mexico:
http://localhost:5000/?culture=es-MX&ui-culture=es-MX
If you only pass in one of the two (culture or ui-culture), the query string provider will set both values using
the one you passed in. For example, setting just the culture will set both the Culture and the UICulture:
http://localhost:5000/?culture=es-MX

CookieRequestCultureProvider

Production apps will often provide a mechanism to set the culture with the ASPNET_CULTURE cookie. The sample
app provides code to set the cookie for French and English cultures.

The Accept-Language HTTP header

The Accept-Language header is settable in most browsers and was originally intended to specify the user’s language.
This setting indicates what the browser has been set to send or has inherited from the underlying operating system. The
Accept-Language HTTP header from a browser request is not an infallible way to detect the user’s preferred language
(see Setting language preferences in a browser). A production app should include a way for a user to customize their
choice of culture.

Setting the Accept-Language HTTP header in IE

1. From the gear icon, tap Internet Options.


2. Tap Languages.

1.4. Fundamentals 163


ASP.NET 5 Documentation, Release

3. Tap Set Language Preferences.


4. Tap Add a language.
5. Add the language.
6. Tap the language, then tap Move Up.

Using a custom provider

Suppose you want to let your customers store their language and culture in your databases. You could write a provider
to look up these values for the user. The following code shows how to add a custom provider:
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr")
};

164 Chapter 1. Topics


ASP.NET 5 Documentation, Release

options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");


options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;

options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =>


{
// My custom request culture logic
return new ProviderCultureResult("en");
}));
});

Use RequestLocalizationOptions to add or remove localization providers.

Resource file naming

Resources are named for the type of their class minus the default namespace (which is also the
name of the assembly). For example, a French resource in the LocalizationWebsite.Web
project for the class LocalizationWebsite.Web.Startup would be named Startup.fr.resx.
The class LocalizationWebsite.Web.Controllers.HomeController would be Con-
trollers.HomeController.fr.resx. If for some reason your targeted class is not in the base namespace you will
need the full type name. For example, in the sample project a type ExtraNamespace.Tools would be
ExtraNamespace.Tools.fr.resx.
In the sample project, the ConfigureServices method sets the ResourcesPath to “Resources”, so the
project relative path for the home controller’s French resource file is Resources/Controllers.HomeController.fr.resx.
Alternatively, you can use folders to organize resource files. For the home controller, the path would be
Resources/Controllers/HomeController.fr.resx. If you don’t use the ResourcesPath option, the .resx file
would go in the project base directory. The resource file for HomeController would be named Con-
trollers.HomeController.fr.resx. The choice of using the dot or path naming convention depends on how you want
to organize your resource files.
Resource name Dot or path naming
Resources/Controllers.HomeController.fr.resx Dot
Resources/Controllers/HomeController.fr.resx Path
Resource files using @inject IViewLocalizer in Razor views follow a similar pattern. The resource file for
a view can be named using either dot naming or path naming. Razor view resource files mimic the path of their
associated view file. Assuming we set the ResourcesPath to “Resources”, the French resource file associated with
the Views/Book/About.cshtml view could be either of the following:
• Resources/Views/Home/About.fr.resx
• Resources/Views.Home.About.fr.resx
If you don’t use the ResourcesPath option, the .resx file for a view would be located in the same folder as the
view.
If you remove the ”.fr” culture designator AND you have the culture set to French (via cookie or other mechanism), the
default resource file is read and strings are localized. The Resource manager designates a default or fallback resource,
when nothing meets your requested culture you’re served the *.resx file without a culture designator. If you want to
just return the key when missing a resource for the requested culture you must not have a default resource file.

Setting the culture programmatically

This sample Localization.StarterWeb project on GitHub contains UI to set the Culture. The
Views/Shared/_SelectLanguagePartial.cshtml file allows you to select the culture from the list of supported cultures:

1.4. Fundamentals 165


ASP.NET 5 Documentation, Release

@using Microsoft.AspNet.Builder
@using Microsoft.AspNet.Http.Features
@using Microsoft.AspNet.Localization
@using Microsoft.AspNet.Mvc.Localization
@using Microsoft.Extensions.Options

@inject IViewLocalizer Localizer


@inject IOptions<RequestLocalizationOptions> LocOptions

@{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
}

<div title="@Localizer["Request culture provider:"] @requestCulture?.Provider?.GetType().Name">


<form id="selectLanguage" asp-controller="Home"
asp-action="SetLanguage" asp-route-returnUrl="@Context.Request.Path"
method="post" class="form-horizontal" role="form">
@Localizer["Language:"] <select name="culture"
asp-for="@requestCulture.RequestCulture.UICulture.Name" asp-items="cultureItems">
</select>
</form>
</div>

The Views/Shared/_SelectLanguagePartial.cshtml file is added to the footer section of the layout file so it will be
available to all views:
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<div class="row">
<div class="col-md-6">
<p>&copy; 2015 - Localization.StarterWeb</p>
</div>
<div class="col-md-6 text-right">
@await Html.PartialAsync("_SelectLanguagePartial")
</div>
</div>
</footer>
</div>

The SetLanguage method sets the culture cookie.


[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);

return LocalRedirect(returnUrl);
}

You can’t simply plug in the _SelectLanguagePartial.cshtml to sample code for this project. The Localiza-

166 Chapter 1. Topics


ASP.NET 5 Documentation, Release

tion.StarterWeb project on GitHub has code to flow the RequestLocalizationOptions to a Razor partial
through the Dependency Injection container.

Globalization and localization terms

The process of localizing your app also requires a basic understanding of relevant character sets commonly used in
modern software development and an understanding of the issues associated with them. Although all computers store
text as numbers (codes), different systems store the same text using different numbers. The localization process refers
to translating the app user interface (UI) for a specific culture/locale.
Localizability is an intermediate process for verifying that a globalized app is ready for localization.
The RFC 4646 format for the culture name is “<languagecode2>-<country/regioncode2>”, where <languagecode2>
is the language code and <country/regioncode2> is the subculture code. For example, es-CL for Spanish (Chile),
en-US for English (United States), and en-AU for English (Australia). RFC 4646 is a combination of an ISO 639
two-letter lowercase culture code associated with a language and an ISO 3166 two-letter uppercase subculture code
associated with a country or region. See Language Culture Name.
Internationalization is often abbreviated to “I18N”. The abbreviation takes the first and last letters and the number of
letters between them, so 18 stands for the number of letters between the first “I” and the last “N”. The same applies to
Globalization (G11N), and Localization (L10N).
Terms:
• Globalization (G11N): The process of making an app support different languages and regions.
• Localization (L10N): The process of customizing an app for a given language and region.
• Internationalization (I18N): Describes both globalization and localization.
• Culture: It is a language and, optionally, a region.
• Neutral culture: A culture that has a specified language, but not a region. (for example “en”, “es”)
• Specific culture: A culture that has a specified language and region. (for example “en-US”, “en-GB”, “es-CL”)
• Locale: A locale is the same as a culture.

Additional Resources

• Localization.StarterWeb project used in the article.


• Resource Files in Visual Studio
• Resources in .resx Files

1.4.8 Configuration

Steve Smith, Daniel Roth


ASP.NET Core supports a variety of different configuration options. Application configuration data can come from
files using built-in support for JSON, XML, and INI formats, as well as from environment variables. You can also
write your own custom configuration provider.

1.4. Fundamentals 167


ASP.NET 5 Documentation, Release

Sections:
• Getting and setting configuration settings
• Using the built-in providers
• Using Options and configuration objects
• Writing custom providers
• Summary

View or download sample code

Getting and setting configuration settings

ASP.NET Core’s configuration system has been re-architected from previous versions of ASP.NET, which relied on
System.Configuration and XML configuration files like web.config. The new configuration model pro-
vides streamlined access to key/value based settings that can be retrieved from a variety of providers. Applications
and frameworks can then access configured settings using the new Options pattern
To work with settings in your ASP.NET application, it is recommended that you only instantiate an instance of
Configuration in your application’s Startup class. Then, use the Options pattern to access individual set-
tings.
At its simplest, the Configuration class is just a collection of Providers, which provide the ability to read and
write name/value pairs. You must configure at least one provider in order for Configuration to function correctly.
The following sample shows how to test working with Configuration as a key/value store:
1 // assumes using Microsoft.Framework.ConfigurationModel is specified
2 var builder = new ConfigurationBuilder();
3 builder.Add(new MemoryConfigurationProvider());
4 var config = builder.Build();
5 config.Set("somekey", "somevalue");
6

7 // do some other work


8

9 string setting2 = config["somekey"]; // also returns "somevalue"

Note: You must set at least one configuration provider.

It’s not unusual to store configuration values in a hierarchical structure, especially when using external files (e.g.
JSON, XML, INI). In this case, configuration values can be retrieved using a : separated key, starting from the root
of the hierarchy. For example, consider the following appsettings.json file:
1 {
2 "ConnectionStrings": {
3 "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplication1-3d6667bc-4e9
4 },
5 "Logging": {
6 "IncludeScopes": false,
7 "LogLevel": {
8 "Default": "Debug",
9 "System": "Information",
10 "Microsoft": "Information"
11 }
12 }
13 }

168 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The application uses configuration to configure the right connection string. Access to the DefaultConnection
setting is achieved through this key: ConnectionStrings:DefaultConnection.
The settings required by your application and the mechanism used to specify those settings (configuration being one
example) can be decoupled using the options pattern. To use the options pattern you create your own settings class
(probably several different classes, corresponding to different cohesive groups of settings) that you can inject into your
application using an options service. You can then specify your settings using configuration or whatever mechanism
you choose.

Note: You could store your Configuration instance as a service, but this would unnecessarily couple your
application to a single configuration system and specific configuration keys. Instead, you can use the Options pattern
to avoid these issues.

Using the built-in providers

The configuration framework has built-in support for JSON, XML, and INI configuration files, as well as support
for in-memory configuration (directly setting values in code) and the ability to pull configuration from environment
variables and command line parameters. Developers are not limited to using a single configuration provider. In fact
several may be set up together such that a default configuration is overridden by settings from another provider if they
are present.
Adding support for additional configuration file providers is accomplished through extension methods. These methods
can be called on a ConfigurationBuilder instance in a standalone fashion, or chained together as a fluent API,
as shown.
1 var config = builder.Build();
2

3 builder.AddEntityFramework(options => options.UseSqlServer(config["Data:DefaultConnection:ConnectionS


4 config = builder.Build();

The order in which configuration providers are specified is important, as this establishes the precedence with which
settings will be applied if they exist in multiple locations. In the example above, if the same setting exists in both
appsettings.json and in an environment variable, the setting from the environment variable will be the one that is
used. The last configuration provider specified “wins” if a setting exists in more than one location. The ASP.NET
team recommends specifying environment variables last, so that the local environment can override anything set in
deployed configuration files.

Note: To override nested keys through environment variables in shells that don’t support : in variable names replace
them with __ (double underscore).

It can be useful to have environment-specific configuration files. This can be achieved using the following:
1 public Startup(IHostingEnvironment env)
2 {
3 var builder = new ConfigurationBuilder()
4 .SetBasePath(env.ContentRootPath)
5 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
6 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
7

8 if (env.IsDevelopment())
9 {
10 // For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID
11 builder.AddUserSecrets();
12 }
13

1.4. Fundamentals 169


ASP.NET 5 Documentation, Release

14 builder.AddEnvironmentVariables();
15 Configuration = builder.Build();

The IHostingEnvironment service is used to get the current environment. In the Development environment,
the highlighted line of code above would look for a file named appsettings.Development.json and use its
values, overriding any other values, if it’s present. Learn more about Working with Multiple Environments.

Warning: You should never store passwords or other sensitive data in provider code or in plain text configuration
files. You also shouldn’t use production secrets in your development or test environments. Instead, such secrets
should be specified outside the project tree, so they cannot be accidentally committed into the provider repository.
Learn more about Working with Multiple Environments and managing Safe storage of app secrets with the Secret
Manager tool.

One way to leverage the order precedence of Configuration is to specify default values, which can be
overridden. In this simple console application, a default value for the username setting is specified in a
MemoryConfigurationProvider, but this is overridden if a command line argument for username is passed
to the application. You can see in the output how many configuration providers are configured at each stage of the
program.
1 using System;
2 using System.Linq;
3 using Microsoft.Extensions.Configuration;
4 using Microsoft.Extensions.Configuration.Memory;
5

6 namespace ConfigConsole
7 {
8 public class Program
9 {
10 public void Main(string[] args)
11 {
12 var builder = new ConfigurationBuilder();
13 Console.WriteLine("Initial Config Providers: " + builder.Providers.Count());
14

15 var defaultSettings = new MemoryConfigurationProvider();


16 defaultSettings.Set("username", "Guest");
17 builder.Add(defaultSettings);
18 Console.WriteLine("Added Memory Provider. Providers: " + builder.Providers.Count());
19

20 builder.AddCommandLine(args);
21 Console.WriteLine("Added Command Line Provider. Providers: " + builder.Providers.Count())
22

23 var config = builder.Build();


24 string username = config["username"];
25

26 Console.WriteLine($"Hello, {username}!");
27 }
28 }
29 }

When run, the program will display the default value unless a command line parameter overrides it.

170 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Using Options and configuration objects

Using the options pattern you can easily convert any class (or POCO - Plain Old CLR Object) into a settings class. It’s
recommended that you create well-factored settings objects that correspond to certain features within your application,
thus following the Interface Segregation Principle (ISP) (classes depend only on the configuration settings they use)
as well as Separation of Concerns (settings for disparate parts of your app are managed separately, and thus are less
likely to negatively impact one another).
A simple MyOptions class is shown here:
1 public class MyOptions
2 {
3 public string Option1 { get; set; }
4 public int Option2 { get; set; }
5 }

Options can be injected into your application using the IOptions<TOptions> service. For example, the following
controller uses IOptions<MyOptions> to access the settings it needs to render the Index view:
1 public class HomeController : Controller
2 {
3 public HomeController(IOptions<MyOptions> optionsAccessor)
4 {
5 Options = optionsAccessor.Value;
6 }
7

8 MyOptions Options { get; }


9

10 // GET: /<controller>/
11 public IActionResult Index()
12 {
13 return View(Options);
14 }
15 }

Learn more about Dependency Injection.


To setup the IOptions<TOption> service you call the AddOptions() extension method during startup in your
ConfigureServices method:
1 public void ConfigureServices(IServiceCollection services)
2 {

1.4. Fundamentals 171


ASP.NET 5 Documentation, Release

3 // Setup options with DI


4 services.AddOptions();
5 }

The Index view displays the configured options:

You configure options using the Configure<TOption> extension method. You can configure options using a
delegate or by binding your options to configuration:
1 public void ConfigureServices(IServiceCollection services)
2 {
3 // Setup options with DI
4 services.AddOptions();
5

6 // Configure MyOptions using config


7 services.Configure<MyOptions>(Configuration);
8

9 // Configure MyOptions using code


10 services.Configure<MyOptions>(myOptions =>
11 {
12 myOptions.Option1 = "value1_from_action";
13 });
14

15 // Add framework services.


16 services.AddMvc();

When you bind options to configuration each property in your options type is bound to a configuration key of the
form property:subproperty:.... For example, the MyOptions.Option1 property is bound to the key
Option1, which is read from the option1 property in appsettings.json. Note that configuration keys are case
insensitive.

172 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Each call to Configure<TOption> adds an IConfigureOptions<TOption> service to the service con-


tainer that is used by the IOptions<TOption> service to provide the configured options to the applica-
tion or framework. If you want to configure your options some other way (ex. reading settings from a
data base) you can use the ConfigureOptions<TOptions> extension method to you specify a custom
IConfigureOptions<TOption> service directly.
You can have multiple IConfigureOptions<TOption> services for the same option type and they are all applied
in order. In the example above value of Option1 and Option2 are both specified in appsettings.json, but the value of
Option1 is overridden by the configured delegate.

Writing custom providers

In addition to using the built-in configuration providers, you can also write your own. To do so, you simply inherit from
ConfigurationProvider, and populate the Data property with the settings from your configuration provider.

Example: Entity Framework Settings

You may wish to store some of your application’s settings in a database, and access them using Entity Framework
(EF). There are many ways in which you could choose to store such values, ranging from a simple table with a column
for the setting name and another column for the setting value, to having separate columns for each setting value. In
this example, I’m going to create a simple configuration provider that reads name-value pairs from a database using
EF.
To start off we’ll define a simple ConfigurationValue entity for storing configuration values in the database:
1 public class ConfigurationValue
2 {
3 public string Id { get; set; }
4 public string Value { get; set; }
5 }

We also need a ConfigurationContext to store and access the configured values using EF:
1 public class ConfigurationContext : DbContext
2 {
3 public ConfigurationContext(DbContextOptions options) : base(options)
4 {
5 }
6

7 public DbSet<ConfigurationValue> Values { get; set; }


8

9 }

Next, create the custom configuration provider by inheriting from ConfigurationProvider. The configuration
data is loaded by overriding the Load method, which reads in all of the configuration data from the configured
database. For demonstration purposes, the configuration provider also takes care of initializing the database if it hasn’t
already been created and populated:
1 public class EntityFrameworkConfigurationProvider : ConfigurationProvider
2 {
3 public EntityFrameworkConfigurationProvider(Action<DbContextOptionsBuilder> optionsAction)
4 {
5 OptionsAction = optionsAction;
6 }
7

8 Action<DbContextOptionsBuilder> OptionsAction { get; }

1.4. Fundamentals 173


ASP.NET 5 Documentation, Release

10 public override void Load()


11 {
12 var builder = new DbContextOptionsBuilder<ConfigurationContext>();
13 OptionsAction(builder);
14

15 using (var dbContext = new ConfigurationContext(builder.Options))


16 {
17 dbContext.Database.EnsureCreated();
18 Data = !dbContext.Values.Any()
19 ? CreateAndSaveDefaultValues(dbContext)
20 : dbContext.Values.ToDictionary(c => c.Id, c => c.Value);
21 }
22 }
23

24 private IDictionary<string, string> CreateAndSaveDefaultValues(ConfigurationContext dbContext)


25 {
26 var configValues = new Dictionary<string, string>
27 {
28 { "key1", "value_from_ef_1" },
29 { "key2", "value_from_ef_2" }
30 };
31 dbContext.Values.AddRange(configValues
32 .Select(kvp => new ConfigurationValue() { Id = kvp.Key, Value = kvp.Value })
33 .ToArray());
34 dbContext.SaveChanges();
35 return configValues;
36 }
37 }

By convention we also add an AddEntityFramework extension method for adding the configuration provider:
1 public static class EntityFrameworkExtensions
2 {
3 public static IConfigurationBuilder AddEntityFramework(this IConfigurationBuilder builder, Action
4 {
5 return builder.Add(new EntityFrameworkConfigurationProvider(setup));
6 }
7 }

You can see an example of how to use this custom ConfigurationProvider in your application in the fol-
lowing example. Create a new ConfigurationBuilder to setup your configuration providers. To add the
EntityFrameworkConfigurationProvider you first need to specify the data provider and connection string.
How should you configure the connection string? Using configuration of course! Add an appsettings.json file as a
configuration provider to bootstrap setting up the EntityFrameworkConfigurationProvider. By reusing
the same ConfigurationBuilder any settings specified in the database will override settings specified in appset-
tings.json:
1 public class Program
2 {
3 public static void Main(string[] args)
4 {
5 var builder = new ConfigurationBuilder();
6 builder.AddJsonFile("appsettings.json");
7 builder.AddEnvironmentVariables();
8 var config = builder.Build();
9

10 builder.AddEntityFramework(options => options.UseSqlServer(config["Data:DefaultConnection:Con


11 config = builder.Build();

174 Chapter 1. Topics


ASP.NET 5 Documentation, Release

12

13 Console.WriteLine("key1={0}", config["key1"]);
14 Console.WriteLine("key2={0}", config["key2"]);
15 Console.WriteLine("key3={0}", config["key3"]);
16

17 }
18 }

Run the application to see the configured values:

Summary

ASP.NET Core provides a very flexible configuration model that supports a number of different file-based options, as
well as command-line, in-memory, and environment variables. It works seamlessly with the options model so that you
can inject strongly typed settings into your application or framework. You can create your own custom configuration
providers as well, which can work with or replace the built-in providers, allowing for extreme flexibility.

1.4.9 Logging

By Steve Smith
ASP.NET Core has built-in support for logging, and allows developers to easily leverage their preferred logging frame-
work’s functionality as well. Implementing logging in your application requires a minimal amount of setup code. Once
this is in place, logging can be added wherever it is desired.

Sections:
• Implementing Logging in your Application
• Configuring Logging in your Application
• Logging Recommendations
• Summary

View or download sample code

1.4. Fundamentals 175


ASP.NET 5 Documentation, Release

Implementing Logging in your Application

Adding logging to a component in your application is done by requesting either an ILoggerFactory or an


ILogger<T> via Dependency Injection. If an ILoggerFactory is requested, a logger must be created using
its CreateLogger method. The following example shows how to do this within the Configure method in the
Startup class:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(minLevel:LogLevel.Verbose);

app.UseStaticFiles();

app.UseMvc();

// Create a catch-all response


app.Run(async (context) =>
{
var logger = loggerFactory.CreateLogger("Catchall Endpoint");
logger.LogInformation("No endpoint found for request {path}", context.Request.Path);
await context.Response.WriteAsync("No endpoint found - try /api/todo.");
});

When a logger is created, a category name must be provided. The category name specifies the source of the logging
events. By convention this string is hierarchical, with categories separated by dot (.) characters. Some logging
providers have filtering support that leverages this convention, making it easier to locate logging output of interest.
In the above example, the logging is configured to use the built-in ConsoleLogger (see Configuring Logging in your
Application below). To see the console logger in action, run the sample application using the web command, and
make a request to configured URL (localhost:5000). You should see output similar to the following:

You may see more than one log statement per web request you make in your browser, since most browsers will make
multiple requests (i.e. for the favicon file) when attempting to load a page. Note that the console logger displayed the
log level (info in the image above) followed by the category ([Catchall Endpoint]), and then the message
that was logged.

176 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The call to the log method can utilize a format string with named placeholders (like {path}). These placeholders are
populated in the order in which they appear by the args values passed into the method call. Some logging providers
will store these names along with their mapped values in a dictionary that can later be queried. In the example below,
the request path is passed in as a named placeholder:
var logger = loggerFactory.CreateLogger("Catchall Endpoint");

In your real world applications, you will want to add logging based on application-level, not framework-level, events.
For instance, if you have created a Web API application for managing To-Do Items (see Building Your First Web
API with ASP.NET Core MVC and Visual Studio), you might add logging around the various operations that can be
performed on these items.
The logic for the API is contained within the TodoController, which uses Dependency Injection to request the services
it requires via its constructor. Ideally, classes should follow this example and use their constructor to define their
dependencies explicitly as parameters. Rather than requesting an ILoggerFactory and creating an instance of ILogger
explicitly, TodoController demonstrates another way to work with loggers in your application - you can request an
ILogger<T> (where T is the class requesting the logger).
[Route("api/[controller]")]
public class TodoController : Controller
{
private readonly ITodoRepository _todoRepository;
private readonly ILogger<TodoController> _logger;

public TodoController(ITodoRepository todoRepository,


ILogger<TodoController> logger)
{
_todoRepository = todoRepository;
_logger = logger;
}

[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
_logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items");
EnsureItems();
return _todoRepository.GetAll();
}

Within each controller action, logging is done through the use of the local field, _logger, as shown on line 17, above.
This technique is not limited to controllers, but can be utilized by any of your application services that utilize Depen-
dency Injection.

Working with ILogger<T>

As we have just seen, your application can request an instance of ILogger<T> as a dependency in a class’s construc-
tor, where T is the type performing logging. The TodoController shows an example of this approach. When this
technique is used, the logger will automatically use the type’s name as its category name. By requesting an instance
of ILogger<T>, your class doesn’t need to create an instance of a logger via ILoggerFactory. You can use this
approach anywhere you don’t need the additional functionality offered by ILoggerFactory.

Logging Verbosity Levels

When adding logging statements to your application, you must specify a LogLevel. The LogLevel allows you to
control the verbosity of the logging output from your application, as well as the ability to pipe different kinds of log

1.4. Fundamentals 177


ASP.NET 5 Documentation, Release

messages to different loggers. For example, you may wish to log debug messages to a local file, but log errors to the
machine’s event log or a database.
ASP.NET Core defines six levels of logging verbosity:
Debug Used for the most detailed log messages, typically only valuable to a developer debugging an issue. These mes-
sages may contain sensitive application data and so should not be enabled in a production environment. Disabled
by default. Example: Credentials: {"User":"someuser", "Password":"P@ssword"}
Verbose These messages have short-term usefulness during development. They contain information that may be
useful for debugging, but have no long-term value. This is the default most verbose level of logging. Example:
Entering method Configure with flag set to true
Information These messages are used to track the general flow of the application. These logs should have some long
term value, as opposed to Verbose level messages, which do not. Example: Request received for
path /foo
Warning The Warning level should be used for abnormal or unexpected events in the application flow. These may
include errors or other conditions that do not cause the application to stop, but which may need to be investi-
gated in the future. Handled exceptions are a common place to use the Warning log level. Examples: Login
failed for IP 127.0.0.1 or FileNotFoundException for file foo.txt
Error An error should be logged when the current flow of the application must stop due to some failure, such as an
exception that cannot be handled or recovered from. These messages should indicate a failure in the current
activity or operation (such as the current HTTP request), not an application-wide failure. Example: Cannot
insert record due to duplicate key violation
Critical A critical log level should be reserved for unrecoverable application or system crashes, or catastrophic failure
that requires immediate attention. Examples: data loss scenarios, out of disk space
The Logging package provides helper extension methods for each of these standard LogLevel values, allowing
you to call LogInformation rather than the more verbose Log(LogLevel.Information, ...) method. Each of the
LogLevel-specific extension methods has several overloads, allowing you to pass in some or all of the following
parameters:
string data The message to log.
int eventId A numeric id to associate with the log, which can be used to associate a series of logged events with one
another. Event IDs should be static and specific to a particular kind of event that is being logged. For instance,
you might associate adding an item to a shopping cart as event id 1000 and completing a purchase as event id
1001. This allows intelligent filtering and processing of log statements.
string format A format string for the log message.
object[] args An array of objects to format.
Exception error An exception instance to log.

Note: Some loggers, such as the built-in ConsoleLogger used in this article, will ignore the eventId parameter.
If you need to display it, you can include it in the message string. This is done in the following sample so you can easily
see the eventId associated with each message, but in practice you would not typically include it in the log message.

In the TodoController example, event id constants are defined for each event, and log statements are configured
at the appropriate verbosity level based on the success of the operation. In this case, successful operations log as
Information and not found results are logged as Warning (error handling is not shown).
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
_logger.LogInformation(LoggingEvents.LIST_ITEMS, "Listing all items");
EnsureItems();

178 Chapter 1. Topics


ASP.NET 5 Documentation, Release

return _todoRepository.GetAll();
}

[HttpGet("{id}", Name = "GetTodo")]


public IActionResult GetById(string id)
{
_logger.LogInformation(LoggingEvents.GET_ITEM, "Getting item {0}", id);
var item = _todoRepository.Find(id);
if (item == null)
{
_logger.LogWarning(LoggingEvents.GET_ITEM_NOTFOUND, "GetById({0}) NOT FOUND", id);
return HttpNotFound();
}
return new ObjectResult(item);
}

Note: It is recommended that you perform application logging at the level of your application and its APIs, not at
the level of the framework. The framework already has logging built in which can be enabled simply by setting the
appropriate logging verbosity level.

To see more detailed logging at the framework level, you can adjust the LogLevel specified to your logging provider to
something more verbose (like Debug or Verbose). For example, if modify the AddConsole call in the Configure method
to use LogLevel.Verbose and run the application, the result shows much framework-level detail about the request:

1.4. Fundamentals 179


ASP.NET 5 Documentation, Release

The console logger prefixes verbose output with “verbose: ” and uses a gray font to make it easier to distinguish it
from other levels of log output.

Scopes

In the course of logging information within your application, you can group a set of logical operations within a scope.
A scope is an IDisposable type returned by calling the BeginScopeImpl method, which lasts from the moment
it is created until it is disposed. The built-in TraceSource logger returns a scope instance that is responsible for
starting and stopping tracing operations. Any logging state, such as a transaction id, is attached to the scope when it is
created.
Scopes are not required, and should be used sparingly, if at all. They’re best used for operations that have a distinct
beginning and end, such as a transaction involving multiple resources.

Configuring Logging in your Application

To configure logging in your ASP.NET application, you should resolve ILoggerFactory in the Configure
method in your Startup class. ASP.NET will automatically provide an instance of ILoggerFactory using

180 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Dependency Injection when you add a parameter of this type to the Configure method. Once you’ve added
ILoggerFactory as a parameter, you configure loggers within the Configure method by calling methods (or ex-
tension methods) on the logger factory. We have already seen an example of this configuration at the beginning of this
article, when we added console logging by simply calling loggerFactory.AddConsole. In addition to adding
loggers, you can also control the verbosity of the application’s logging by setting the MinimumLevel property on
the logger factory. The default verbosity is Verbose.

Note: You can specify the minimum logging level each logger provider will use as well. For example, the
AddConsole extension method supports an optional parameter for setting its minimum LogLevel.

Configuring TraceSource Logging

When running on the full .NET Framework you can configuring logging to use the existing Sys-
tem.Diagnostics.TraceSource libraries and providers, including easy access to the Windows event log.
TraceSource allows you to route messages to a variety of listeners and is already in use by many organizations.
First, be sure to add the Microsoft.Extensions.Logging.TraceSource package to your project (in
project.json):
"dependencies": {
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
"Microsoft.Extensions.Logging.TraceSource": "1.0.0-rc1-final"
},

The following example demonstrates how to configure two separate TraceSourceLogger instances for an appli-
cation, both logging only Critical messages. Each call to AddTraceSource takes a TraceListener. The
first call configures a ConsoleTraceListener; the second one configures an EventLogTraceListener to
write to the Application event log. These two listeners are not available in .NET Core, so their configuration is
wrapped in a conditional compilation statement.
loggerFactory.MinimumLevel = LogLevel.Debug;
#if DNX451
var sourceSwitch = new SourceSwitch("LoggingSample");
sourceSwitch.Level = SourceLevels.Critical;
loggerFactory.AddTraceSource(sourceSwitch,
new ConsoleTraceListener(false));
loggerFactory.AddTraceSource(sourceSwitch,
new EventLogTraceListener("Application"));
#endif

The sample above also demonstrates setting the MinimumLevel on the logger factory. However, this specified level
is simply the default for new factories, but can still be overridden by individually configured loggers. In this case, the
sourceSwitch is configured to use SourceLevels.Critical, so only Critical log messages are picked
up by the two TraceListener instances.
To test out this code, replace the catch-all response with the following app.Run block:
app.Run(async context =>
{
if (context.Request.Path.Value.Contains("boom"))
{
throw new Exception("boom!");
}

1.4. Fundamentals 181


ASP.NET 5 Documentation, Release

await context.Response.WriteAsync("Hello World!");


});

With this change in place, when the application is run (on Windows), and a request is made to
http://localhost:5000/boom, the following is shown in the console output:

Examining the Application event log in the Windows Event Viewer, the following event has also been logged as a
result of this request:

182 Chapter 1. Topics


ASP.NET 5 Documentation, Release

In addition to working with TraceSourceLogger, you can also log directly to the event log using the EventLog logging
provider. Support for logging using System.Diagnostics.Debug.WriteLine is also available using the Debug logging
provider, the output of which can be seen in Visual Studio’s Output window.

Configuring Other Providers

In addition to the built-in loggers, you can configure logging to use other providers. Add the appropriate package
to your project.json file, and then configure it just like any other provider. Typically, these packages should include
extension methods on ILoggerFactory to make it easy to add them.

Note: The ASP.NET team is still working with third party logging providers to publish support for this logging
model. Once these ship, we will include links to them here.

You can create your own custom providers as well, to support other logging frameworks or your own internal logging
requirements.

Logging Recommendations

The following are some recommendations you may find helpful when implementing logging in your ASP.NET appli-
cations.
1. Log using the correct LogLevel. This will allow you to consume and route logging output appropriately based
on the importance of the messages.

1.4. Fundamentals 183


ASP.NET 5 Documentation, Release

2. Log information that will enable errors to be identified quickly. Avoid logging irrelevant or redundant informa-
tion.
3. Keep log messages concise without sacrificing important information.
4. Although loggers will not log if disabled, consider adding code guards around logging methods to prevent extra
method calls and log message setup overhead, especially within loops and performance critical methods.
5. Name your loggers with a distinct prefix so they can easily be filtered or disabled. Remember the Create<T>
extension will create loggers named with the full name of the class.
6. Use Scopes sparingly, and only for actions with a bounded start and end. For example, the framework provides
a scope around MVC actions. Avoid nesting many scopes within one another.
7. Application logging code should be related to the business concerns of the application. Increase the logging
verbosity to reveal additional framework-related concerns, rather than implementing yourself.

Summary

ASP.NET provides built-in support for logging, which can easily be configured within the Startup class and used
throughout the application. Logging verbosity can be configured globally and per logging provider to ensure action-
able information is logged appropriately. Built-in providers for console and trace source logging are included in the
framework; other logging frameworks can easily be configured as well.

1.4.10 File Providers

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

1.4.11 Dependency Injection

Steve Smith
ASP.NET Core is designed from the ground up to support and leverage dependency injection. ASP.NET Core ap-
plications can leverage built-in framework services by having them injected into methods in the Startup class, and
application services can be configured for injection as well. The default services container provided by ASP.NET
Core provides a minimal feature set and is not intended to replace other containers.

184 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Sections:
• What is Dependency Injection?
• Using Framework-Provided Services
• Registering Your Own Services
• Service Lifetimes and Registration Options
• Request Services
• Designing Your Services For Dependency Injection
• Replacing the default services container
• Recommendations
• Additional Resources

View or download sample code

What is Dependency Injection?

Dependency injection (DI) is a technique for achieving loose coupling between objects and their collaborators, or
dependencies. Rather than directly instantiating collaborators, or using static references, the objects a class needs in
order to perform its actions are provided to the class in some fashion. Most often, classes will declare their depen-
dencies via their constructor, allowing them to follow the Explicit Dependencies Principle. This approach is known as
“constructor injection”.
When classes are designed with DI in mind, they are more loosely coupled because they do not have direct, hard-
coded dependencies on their collaborators. This follows the Dependency Inversion Principle, which states that “high
level modules should not depend on low level modules; both should depend on abstractions.” Instead of referencing
specific implementations, classes request abstractions (typically interfaces) which are provided to them when
they are constructed. Extracting dependencies into interfaces and providing implementations of these interfaces as
parameters is also an example of the Strategy design pattern.
When a system is designed to use DI, with many classes requesting their dependencies via their constructor (or prop-
erties), it’s helpful to have a class dedicated to creating these classes with their associated dependencies. These classes
are referred to as containers, or more specifically, Inversion of Control (IoC) containers or Dependency Injection (DI)
containers. A container is essentially a factory that is responsible for providing instances of types that are requested
from it. If a given type has declared that it has dependencies, and the container has been configured to provide the
dependency types, it will create the dependencies as part of creating the requested instance. In this way, complex
dependency graphs can be provided to classes without the need for any hard-coded object construction. In addition to
creating objects with their dependencies, containers typically manage object lifetimes within the application.
ASP.NET Core includes a simple built-in container (represented by the IServiceProvider interface) that sup-
ports constructor injection by default, and ASP.NET makes certain services available through DI. ASP.NET’s container
refers to the types it manages as services. Throughout the rest of this article, services will refer to types that are man-
aged by ASP.NET Core’s IoC container. You configure the built-in container’s services in the ConfigureServices
method in your application’s Startup class.

Note: Martin Fowler has written an extensive article on Inversion of Control Containers and the Dependency Injection
Pattern. Microsoft Patterns and Practices also has a great description of Dependency Injection.

Note: This article covers Dependency Injection as it applies to all ASP.NET applications. Dependency Injection
within MVC controllers is covered in Dependency Injection and Controllers.

1.4. Fundamentals 185


ASP.NET 5 Documentation, Release

Using Framework-Provided Services

The ConfigureServices method in the Startup class is responsible for defining the services the applica-
tion will use, including platform features like Entity Framework Core and ASP.NET Core MVC. Initially, the
IServiceCollection provided to ConfigureServices has just a handful of services defined. Below
is an example of how to add additional services to the container using a number of extensions methods like
AddDbContext, AddIdentity, and AddMvc.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();

services.AddMvc();

// Add application services.


services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}

The features and middleware provided by ASP.NET, such as MVC, follow a convention of using a single AddService
extension method to register all of the services required by that feature.

Tip: You can request certain framework-provided services within Startup methods through their parameter lists -
see Application Startup for more details.

Of course, in addition to configuring the application to take advantage of various framework features, you can also use
ConfigureServices to configure your own application services.

Registering Your Own Services

You can register your own application services as follows. The first generic type represents the type (typically an
interface) that will be requested from the container. The second generic type represents the concrete type that will be
instantiated by the container and used to fulfill such requests.
services.AddTransient<ISmsSender, AuthMessageSender>();

Note: Each services.Add<service> calls adds (and potentially configures) services. For example,
services.AddMvc() adds the services MVC requires.

The AddTransient method is used to map abstract types to concrete services that are instantiated separately for
every object that requires it. This is known as the service’s lifetime, and additional lifetime options are described
below. It is important to choose an appropriate lifetime for each of the services you register. Should a new instance of
the service be provided to each class that requests it? Should one instance be used throughout a given web request?
Or should a single instance be used for the lifetime of the application?
In the sample for this article, there is a simple controller that displays character names, called
CharactersController. Its Index method displays the current list of characters that have been stored in
the application, and initializes the collection with a handful of characters if none exist. Note that although this ap-
plication uses Entity Framework Core and the ApplicationDbContext class for its persistence, none of that

186 Chapter 1. Topics


ASP.NET 5 Documentation, Release

is apparent in the controller. Instead, the specific data access mechanism has been abstracted behind an interface,
ICharacterRepository, which follows the repository pattern. An instance of ICharacterRepository is
requested via the constructor and assigned to a private field, which is then used to access characters as necessary.
public class CharactersController : Controller
{
private readonly ICharacterRepository _characterRepository;

public CharactersController(ICharacterRepository characterRepository)


{
_characterRepository = characterRepository;
}

// GET: /characters/
public IActionResult Index()
{
PopulateCharactersIfNoneExist();
var characters = _characterRepository.ListAll();

return View(characters);
}

private void PopulateCharactersIfNoneExist()


{
if (!_characterRepository.ListAll().Any())
{
_characterRepository.Add(new Character("Darth Maul"));
_characterRepository.Add(new Character("Darth Vader"));
_characterRepository.Add(new Character("Yoda"));
_characterRepository.Add(new Character("Mace Windu"));
}
}
}

The ICharacterRepository simply defines the two methods the controller needs to work with Character instances.
using System.Collections.Generic;
using DependencyInjectionSample.Models;

namespace DependencyInjectionSample.Interfaces
{
public interface ICharacterRepository
{
IEnumerable<Character> ListAll();
void Add(Character character);
}
}

This interface is in turn implemented by a concrete type, CharacterRepository, that is used at runtime.

Note: The way DI is used with the CharacterRepository class is a general model you can follow for all of
your application services, not just in “repositories” or data access classes.

using System.Collections.Generic;
using System.Linq;
using DependencyInjectionSample.Interfaces;

namespace DependencyInjectionSample.Models

1.4. Fundamentals 187


ASP.NET 5 Documentation, Release

{
public class CharacterRepository : ICharacterRepository
{
private readonly ApplicationDbContext _dbContext;

public CharacterRepository(ApplicationDbContext dbContext)


{
_dbContext = dbContext;
}

public IEnumerable<Character> ListAll()


{
return _dbContext.Characters.AsEnumerable();
}

public void Add(Character character)


{
_dbContext.Characters.Add(character);
_dbContext.SaveChanges();
}
}
}

Note that CharacterRepository requests an ApplicationDbContext in its constructor. It is not unusual


for dependency injection to be used in a chained fashion like this, with each requested dependency in turn requesting
its own dependencies. The container is responsible for resolving all of the dependencies in the graph and returning the
fully resolved service.

Note: Creating the requested object, and all of the objects it requires, and all of the objects those require, is sometimes
referred to as an object graph. Likewise, the collective set of dependencies that must be resolved is typically referred
to as a dependency tree or dependency graph.

In this case, both ICharacterRepository and in turn ApplicationDbContext must be registered with
the services container in ConfigureServices in Startup. ApplicationDbContext is configured
with the call to the extension method AddDbContext<T>. The following code shows the registration of the
CharacterRepository type.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseInMemoryDatabase()
);

// Add framework services.


services.AddMvc();

// Register application services.


services.AddScoped<ICharacterRepository, CharacterRepository>();
services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();
}

Entity Framework contexts should be added to the services container using the Scoped lifetime. This is taken care
of automatically if you use the helper methods as shown above. Repositories that will make use of Entity Framework

188 Chapter 1. Topics


ASP.NET 5 Documentation, Release

should use the same lifetime.

Warning: The main danger to be wary of is resolving a Scoped service from a singleton. It’s likely in such a
case that the service will have incorrect state when processing subsequent requests.

Service Lifetimes and Registration Options

ASP.NET services can be configured with the following lifetimes:


Transient Transient lifetime services are created each time they are requested. This lifetime works best for
lightweight, stateless services.
Scoped Scoped lifetime services are created once per request.
Singleton Singleton lifetime services are created the first time they are requested (or when ConfigureServices
is run if you specify an instance there) and then every subsequent request will use the same instance. If your
application requires singleton behavior, allowing the services container to manage the service’s lifetime is rec-
ommended instead of implementing the singleton design pattern and managing your object’s lifetime in the class
yourself.
Services can be registered with the container in several ways. We have already seen how to register a service imple-
mentation with a given type by specifying the concrete type to use. In addition, a factory can be specified, which will
then be used to create the instance on demand. The third approach is to directly specify the instance of the type to use,
in which case the container will never attempt to create an instance.
To demonstrate the difference between these lifetime and registration options, consider a simple interface that repre-
sents one or more tasks as an operation with a unique identifier, OperationId. Depending on how we configure the
lifetime for this service, the container will provide either the same or different instances of the service to the requesting
class. To make it clear which lifetime is being requested, we will create one type per lifetime option:
using System;

namespace DependencyInjectionSample.Interfaces
{
public interface IOperation
{
Guid OperationId { get; }
}

public interface IOperationTransient : IOperation


{
}
public interface IOperationScoped : IOperation
{
}
public interface IOperationSingleton : IOperation
{
}
public interface IOperationSingletonInstance : IOperation
{
}
}

We implement these interfaces using a single class, Operation, that accepts a Guid in its constructor, or uses a new
Guid if none is provided.
Next, in ConfigureServices, each type is added to the container according to its named lifetime:

1.4. Fundamentals 189


ASP.NET 5 Documentation, Release

services.AddTransient<IOperationTransient, Operation>();
services.AddScoped<IOperationScoped, Operation>();
services.AddSingleton<IOperationSingleton, Operation>();
services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));
services.AddTransient<OperationService, OperationService>();

Note that the IOperationSingletonInstance service is using a specific instance with a known ID of
Guid.Empty so it will be clear when this type is in use. We have also registered an OperationService that
depends on each of the other Operation types, so that it will be clear within a request whether this service is get-
ting the same instance as the controller, or a new one, for each operation type. All this service does is expose its
dependencies as properties, so they can be displayed in the view.
using DependencyInjectionSample.Interfaces;

namespace DependencyInjectionSample.Services
{
public class OperationService
{
public IOperationTransient TransientOperation { get; }
public IOperationScoped ScopedOperation { get; }
public IOperationSingleton SingletonOperation { get; }
public IOperationSingletonInstance SingletonInstanceOperation { get; }

public OperationService(IOperationTransient transientOperation,


IOperationScoped scopedOperation,
IOperationSingleton singletonOperation,
IOperationSingletonInstance instanceOperation)
{
TransientOperation = transientOperation;
ScopedOperation = scopedOperation;
SingletonOperation = singletonOperation;
SingletonInstanceOperation = instanceOperation;
}
}
}

To demonstrate the object lifetimes within and between separate individual requests to the application, the
sample includes an OperationsController that requests each kind of IOperation type as well as an
OperationService. The Index action then displays all of the controller’s and service’s OperationId val-
ues.
using DependencyInjectionSample.Interfaces;
using DependencyInjectionSample.Services;
using Microsoft.AspNetCore.Mvc;

namespace DependencyInjectionSample.Controllers
{
public class OperationsController : Controller
{
private readonly OperationService _operationService;
private readonly IOperationTransient _transientOperation;
private readonly IOperationScoped _scopedOperation;
private readonly IOperationSingleton _singletonOperation;
private readonly IOperationSingletonInstance _singletonInstanceOperation;

public OperationsController(OperationService operationService,


IOperationTransient transientOperation,
IOperationScoped scopedOperation,

190 Chapter 1. Topics


ASP.NET 5 Documentation, Release

IOperationSingleton singletonOperation,
IOperationSingletonInstance singletonInstanceOperation)
{
_operationService = operationService;
_transientOperation = transientOperation;
_scopedOperation = scopedOperation;
_singletonOperation = singletonOperation;
_singletonInstanceOperation = singletonInstanceOperation;
}

public IActionResult Index()


{
// viewbag contains controller-requested services
ViewBag.Transient = _transientOperation;
ViewBag.Scoped = _scopedOperation;
ViewBag.Singleton = _singletonOperation;
ViewBag.SingletonInstance = _singletonInstanceOperation;

// operation service has its own requested services


ViewBag.Service = _operationService;
return View();
}
}
}

Now two separate requests are made to this controller action:

1.4. Fundamentals 191


ASP.NET 5 Documentation, Release

Observe which of the OperationId values varies within a request, and between requests.
• Transient objects are always different; a new instance is provided to every controller and every service.
• Scoped objects are the same within a request, but different across different requests
• Singleton objects are the same for every object and every request (regardless of whether an instance is provided
in ConfigureServices)

Request Services

The services available within an ASP.NET request from HttpContext are exposed through the
RequestServices collection.

Request Services represent the services you configure and request as part of your application. When your objects spec-
ify dependencies, these are satisfied by the types found in RequestServices, not ApplicationServices.
Generally, you shouldn’t use these properties directly, preferring instead to request the types your classes you require
via your class’s constructor, and letting the framework inject these dependencies. This yields classes that are easier to
test (see Testing) and are more loosely coupled.

Note: Prefer requesting dependencies as constructor parameters to accessing the RequestServices collection.

192 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Designing Your Services For Dependency Injection

You should design your services to use dependency injection to get their collaborators. This means avoiding the use of
stateful static method calls (which result in a code smell known as static cling) and the direct instantiation of dependent
classes within your services. It may help to remember the phrase, New is Glue, when choosing whether to instantiate
a type or to request it via dependency injection. By following the SOLID Principles of Object Oriented Design, your
classes will naturally tend to be small, well-factored, and easily tested.
What if you find that your classes tend to have way too many dependencies being injected? This is generally a sign
that your class is trying to do too much, and is probably violating SRP - the Single Responsibility Principle. See if you
can refactor the class by moving some of its responsibilities into a new class. Keep in mind that your Controller
classes should be focused on UI concerns, so business rules and data access implementation details should be kept in
classes appropriate to these separate concerns.
With regard to data access specifically, you can easily inject Entity Framework DbContext types into your con-
trollers, assuming you’ve configured EF in your Startup class. However, it is best to avoid depending directly on
DbContext in your UI project. Instead, depend on an abstraction (like a Repository interface), and restrict knowl-
edge of EF (or any other specific data access technology) to the implementation of this interface. This will reduce the
coupling between your application and a particular data access strategy, and will make testing your application code
much easier.

Replacing the default services container

The built-in services container is mean to serve the basic needs of the framework and most consumer applications
built on it. However, developers who wish to replace the built-in container with their preferred container can eas-
ily do so. The ConfigureServices method typically returns void, but if its signature is changed to return
IServiceProvider, a different container can be configured and returned. There are many IOC containers avail-
able for .NET. In this example, the Autofac package is used.
First, add the appropriate container package(s) to the dependencies property in project.json:
"dependencies" : {
"Autofac": "4.0.0-rc2-237",
"Autofac.Extensions.DependencyInjection": "4.0.0-rc2-200"
},

Next, configure the container in ConfigureServices and return an IServiceProvider:


public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// add other framework services

// Add Autofac
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterModule<DefaultModule>();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return container.Resolve<IServiceProvider>();
}

Note: When using a third-party DI container, you must change ConfigureServices so that it returns
IServiceProvider instead of void.

1.4. Fundamentals 193


ASP.NET 5 Documentation, Release

Finally, configure Autofac as normal in DefaultModule:


public class DefaultModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<CharacterRepository>().As<ICharacterRepository>();
}
}

At runtime, Autofac will be used to resolve types and inject dependencies. Learn more about using Autofac and
ASP.NET Core

Recommendations

When working with dependency injection, keep the following recommendations in mind:
• DI is for objects that have complex dependencies. Controllers, services, adapters, and repositories are all exam-
ples of objects that might be added to DI.
• Avoid storing data and configuration directly in DI. For example, a user’s shopping cart shouldn’t typically be
added to the services container. Configuration should use the Options Model. Similarly, avoid “data holder”
objects that only exist to allow access to some other object. It’s better to request the actual item needed via DI,
if possible.
• Avoid static access to services.
• Avoid service location in your application code.
• Avoid static access to HttpContext.

Note: Like all sets of recommendations, you may encounter situations where ignoring one is required. We have found
exceptions to be rare – mostly very special cases within the framework itself.

Remember, dependency injection is an alternative to static/global object access patterns. You will not be able to realize
the benefits of DI if you mix it with static object access.

Additional Resources

• Application Startup
• Testing
• Writing Clean Code in ASP.NET Core with Dependency Injection (MSDN)
• Container-Managed Application Design, Prelude: Where does the Container Belong?
• Explicit Dependencies Principle
• Inversion of Control Containers and the Dependency Injection Pattern (Fowler)

1.4.12 Working with Multiple Environments

By Steve Smith
ASP.NET Core introduces improved support for controlling application behavior across multiple environments, such as
development, staging, and production. Environment variables are used to indicate which environment the application
is running in, allowing the app to be configured appropriately.

194 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Sections:
• Development, Staging, Production
• Determining the environment at runtime
• Startup conventions
• Summary
• Additional Resources

View or download sample code

Development, Staging, Production

ASP.NET Core references a particular environment variable, Hosting:Environment (or


Hosting__Environment on *nix systems), to describe the environment the application is currently run-
ning in. This variable can be set to any value you like, but three values are used by convention: Development,
Staging, and Production. You will find these values used in the samples and templates provided with ASP.NET
Core.
The current environment setting can be detected programmatically from within your application. In addition, you can
use the Environment tag helper to include certain sections in your view based on the current application environment.

Note: The specified environment name is case insensitive. Whether you set the variable to Development or
development or DEVELOPMENT the results will be the same.

Development

This should be the environment used when developing an application. When using Visual Studio, this setting can be
specified in your project’s debug profiles, such as for IIS Express, shown here:

When you modify the default settings created with the project, your changes are persisted in launchSettings.json in
the Properties folder. This file holds settings specific to each profile Visual Studio is configured to use to launch
the application, including any environment variables that should be used. (Debug profiles are discussed in more detail

1.4. Fundamentals 195


ASP.NET 5 Documentation, Release

in Servers). After modifying the Hosting:Environment variable in the web profile to be set to Staging, the
launchSettings.json file in our sample project is shown below:

Listing 1.3: launchSettings.json


1 {
2 "iisSettings": {
3 "windowsAuthentication": false,
4 "anonymousAuthentication": true,
5 "iisExpress": {
6 "applicationUrl": "http://localhost:40088/",
7 "sslPort": 0
8 }
9 },
10 "profiles": {
11 "IIS Express": {
12 "commandName": "IISExpress",
13 "launchBrowser": true,
14 "environmentVariables": {
15 "ASPNET_ENV": "Development"
16 }
17 },
18 "web": {
19 "commandName": "web",
20 "environmentVariables": {
21 "Hosting:Environment": "Staging"
22 }
23 }
24 }
25 }

Note: Changes made to project profiles or to launchSettings.json directly may not take effect until the web server
used is restarted (in particular, kestrel must be restarted before it will detect changes made to its environment).

Staging

By convention, a Staging environment is a pre-production environment used for final testing before deployment to
production. Ideally, its physical characteristics should mirror that of production, so that any issues that may arise in
production occur first in the staging environment, where they can be addressed without impact to users.

Production

The Production environment is the environment in which the application runs when it is live and being used by end
users. This environment should be configured to maximize security, performance, and application robustness. Some
common settings that a production environment might have that would differ from development include:
• Turn on caching
• Ensure all client-side resources are bundled, minified, and potentially served from a CDN
• Turn off diagnostic ErrorPages
• Turn on friendly error pages
• Enable production logging and monitoring (for example, Application Insights)

196 Chapter 1. Topics


ASP.NET 5 Documentation, Release

This is by no means meant to be a complete list. It’s best to avoid scattering environment checks in many parts of
your application. Instead, the recommended approach is to perform such checks within the application’s Startup
class(es) wherever possible

Determining the environment at runtime

The IHostingEnvironment service provides the core abstraction for working with environments. This service
is provided by the ASP.NET hosting layer, and can be injected into your startup logic via Dependency Injection. The
ASP.NET Core web site template in Visual Studio uses this approach to load environment-specific configuration files
(if present) and to customize the app’s error handling settings. In both cases, this behavior is achieved by referring
to the currently specified environment by calling EnvironmentName or IsEnvironment on the instance of
IHostingEnvironment passed into the appropriate method.
If you need to check whether the application is running in a particular environment, use
env.IsEnvironment("environmentname") since it will correctly ignore case (instead of checking if
env.EnvironmentName == "Development" for example).
For example, you can use the following code in you Configure method to setup environment specific error handling:
1 if (env.IsDevelopment())
2 {
3 app.UseDeveloperExceptionPage();
4 app.UseDatabaseErrorPage();
5 app.UseBrowserLink();
6 }
7 else
8 {
9 app.UseExceptionHandler("/Home/Error");
10 }

If the app is running in a Development environment, then it enables BrowserLink and development specific error
pages (which typically should not be run in production). Otherwise, if the app is not running in a development
environment, a standard error handling page is configured to be displayed in response to any unhandled exceptions.
You may need to determine which content to send to the client at runtime, depending on the current environment.
For example, in a development environment you generally serve non-minimized scripts and style sheets, which makes
debugging easier. Production and test environments should serve the minified versions and generally from a CDN.
You can do this using the Environment tag helper. The Environment tag helper will only render its contents if the
current environment matches one of the environments specified using the names attribute.
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.min.cs
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-v
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>

To get started with using tag helpers in your application see Introduction to Tag Helpers.

Startup conventions

ASP.NET Core supports a convention-based approach to configuring an application’s startup based on the current
environment. You can also programmatically control how your application behaves according to which environment

1.4. Fundamentals 197


ASP.NET 5 Documentation, Release

it is in, allowing you to create and manage your own conventions.


When an ASP.NET Core application starts, the Startup class is used to bootstrap the application, load
its configuration settings, etc. (learn more about ASP.NET startup). However, if a class exists named
Startup{EnvironmentName} (for example StartupDevelopment), and the Hosting:Environment
environment variable matches that name, then that Startup class is used instead. Thus, you could configure
Startup for development, but have a separate StartupProduction that would be used when the app is run
in production. Or vice versa.
The following StartupDevelopment file from this article’s sample project is run when the application is set to
run in a Development environment:

Listing 1.4: StartupDevelopment.cs


1 using Microsoft.AspNet.Builder;
2

3 namespace Environments
4 {
5 public class StartupDevelopment
6 {
7 public void Configure(IApplicationBuilder app)
8 {
9 app.UseWelcomePage();
10 }
11 }
12 }

Run the application in development, and a welcome screen is displayed. The sample also includes a
StartupStaging class:

Listing 1.5: StartupStaging.cs


1 using Microsoft.AspNet.Builder;
2 using Microsoft.AspNet.Http;
3

4 namespace Environments
5 {
6 public class StartupStaging
7 {
8 public void Configure(IApplicationBuilder app)
9 {
10 app.Run(async context =>
11 {
12 context.Response.ContentType = "text/plain";
13 await context.Response.WriteAsync("Staging environment.");
14 });
15 }
16 }
17 }

When the application is run with Hosting:Environment set to Staging, the StartupStaging class is used,
and the application will simply display a string stating it’s running in a staging environment. The application’s default
Startup class will only run when the environment is not set to either Development or Staging (presumably,
this would be when it is set to Production, but you’re not limited to only these three options. Also note that if no
environment is set, the default Startup will run).
In addition to using an entirely separate Startup class based on the current environment, you can also
make adjustments to how the application is configured within a Startup class. The Configure() and
ConfigureServices() methods support environment-specific versions similar to the Startup class itself,

198 Chapter 1. Topics


ASP.NET 5 Documentation, Release

of the form Configure[Environment]() and Configure[Environment]Services(). If you de-


fine a method ConfigureDevelopment() it will be called instead of Configure() when the environ-
ment is set to development. Likewise, ConfigureDevelopmentServices() would be called instead of
ConfigureServices() in the same environment.

Summary

ASP.NET Core provides a number of features and conventions that allow developers to easily control how their appli-
cations behave in different environments. When publishing an application from development to staging to production,
environment variables set appropriately for the environment allow for optimization of the application for debugging,
testing, or production use, as appropriate.

Additional Resources

• Configuration
• Introduction to Tag Helpers

1.4.13 Managing Application State

By Steve Smith
In ASP.NET Core, application state can be managed in a variety of ways, depending on when and how the state is to be
retrieved. This article provides a brief overview of several options, and focuses on installing and configuring Session
state support in ASP.NET Core applications.

Sections
• Application State Options
• Working with HttpContext.Items
• Installing and Configuring Session
• A Working Sample Using Session

View or download sample code

Application State Options

Application state refers to any data that is used to represent the current representation of the application. This includes
both global and user-specific data. Previous versions of ASP.NET (and even ASP) have had built-in support for global
Application and Session state stores, as well as a variety of other options.

Note: The Application store had the same characteristics as the ASP.NET Cache, with fewer capabilities. In
ASP.NET Core, Application no longer exists; applications written for previous versions of ASP.NET that are
migrating to ASP.NET Core replace Application with a Caching implementation.

Application developers are free to use different state storage providers depending on a variety of factors:
• How long does the data need to persist?
• How large is the data?
• What format is the data?

1.4. Fundamentals 199


ASP.NET 5 Documentation, Release

• Can it be serialized?
• How sensitive was the data? Could it be stored on the client?
Based on answers to these questions, application state in ASP.NET Core apps can be stored or managed in a variety of
ways.

HttpContext.Items

The Items collection is the best location to store data that is only needed while processing a given request. Its contents
are discarded after each request. It is best used as a means of communicating between components or middleware that
operate at different points in time during a request, and have no direct relationship with one another through which to
pass parameters or return values. See Working with HttpContext.Items, below.

Querystring and Post

State from one request can be provided to another request by adding values to the new request’s querystring or by
POSTing the data. These techniques should not be used with sensitive data, because these techniques require that the
data be sent to the client and then sent back to the server. It is also best used with small amounts of data. Querystrings
are especially useful for capturing state in a persistent manner, allowing links with embedded state to be created
and sent via email or social networks, for use potentially far into the future. However, no assumption can be made
about the user making the request, since URLs with querystrings can easily be shared, and care must also be taken
to avoid Cross-Site Request Forgery (CSRF) attacks (for instance, even assuming only authenticated users are able to
perform actions using querystring-based URLs, an attacker could trick a user into visiting such a URL while already
authenticated).

Cookies

Very small pieces of state-related data can be stored in Cookies. These are sent with every request, and so the size
should be kept to a minimum. Ideally, only an identifier should be used, with the actual data stored somewhere on the
server, keyed to the identifier.

Session

Session storage relies on a cookie-based identifier to access data related to a given browser session (a series of requests
from a particular browser and machine). You can’t necessarily assume that a session is restricted to a single user, so
be careful what kind of information you store in Session. It is a good place to store application state that is specific to
a particular session but which doesn’t need to be persisted permanently (or which can be reproduced as needed from a
persistent store). See Installing and Configuring Session, below for more details.

Cache

Caching provides a means of storing and efficiently retrieving arbitrary application data based on developer-defined
keys. It provides rules for expiring cached items based on time and other considerations. Learn more about Caching.

Configuration

Configuration can be thought of as another form of application state storage, though typically it is read-only while the
application is running. Learn more about Configuration.

200 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Other Persistence

Any other form of persistent storage, whether using Entity Framework and a database or something like Azure Table
Storage, can also be used to store application state, but these fall outside of what ASP.NET supports directly.

Working with HttpContext.Items

The HttpContext abstraction provides support for a simple dictionary collection of type
IDictionary<object, object>, called Items. This collection is available from the start of an HttpRequest‘
and is discarded at the end of each request. You can access it by simply assigning a value to a keyed entry, or by
requesting the value for a given key.
For example, some simple Middleware could add something to the Items collection:
app.Use(async (context, next) =>
{
// perform some verification
context.Items["isVerified"] = true;
await next.Invoke();
});

and later in the pipeline, another piece of middleware could access it:
app.Run(async (context) =>
{
await context.Response.WriteAsync("Verified request? "
+ context.Items["isVerified"]);
});

Note: Since keys into Items are simple strings, if you are developing middleware that needs to work across many
applications, you may wish to prefix your keys with a unique identifier to avoid key collisions (e.g. “MyCompo-
nent.isVerified” instead of just “isVerified”).

Installing and Configuring Session

ASP.NET Core ships a session package that provides middleware for managing session state. You can install it by
including a reference to the package in your project.json file:
1 "dependencies": {
2 "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
3 "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
4 "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
5 "Microsoft.AspNet.Session": "1.0.0-rc1-final",
6 "Microsoft.Extensions.Caching.Memory": "1.0.0-rc1-final",
7 "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
8 "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
9 "Newtonsoft.Json": "7.0.1"
10 },

Once the package is installed, Session must be configured in your application’s Startup class. Session is built on
top of IDistributedCache, so you must configure this as well, otherwise you will receive an error.

Note: If you do not configure at least one IDistributedCache implementation, you will get an exception stating
“Unable to resolve service for type ‘Microsoft.Framework.Caching.Distributed.IDistributedCache’ while attempting
to activate ‘Microsoft.AspNet.Session.DistributedSessionStore’.”

1.4. Fundamentals 201


ASP.NET 5 Documentation, Release

ASP.NET ships with several implementations of IDistributedCache, including an in-memory option (to be
used during development and testing only). To configure session using this in-memory option, add the following to
ConfigureServices:
services.AddCaching();
services.AddSession();

Then, add the following to Configure and you’re ready to use session in your application code:
app.UseSession();

You can reference Session from HttpContext once it is installed and configured.

Note: If you attempt to access Session before UseSession has been called, you will get an
InvalidOperationException exception stating that “Session has not been configured for this application or
request.”

Warning: If you attempt to create a new Session (i.e. no session cookie has been created yet) after you
have already begun writing to the Response stream, you will get an InvalidOperationException as
well, stating that “The session cannot be established after the response has started”. This exception may not be
displayed in the browser; you may need to view the web server log to discover it, as shown below:

202 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Implementation Details

Session uses a cookie to track and disambiguate between requests from different browsers. By default this cookie is
named ”.AspNet.Session” and uses a path of “/”. Further, by default this cookie does not specify a domain, and is not
made available to client-side script on the page (because CookieHttpOnly defaults to true).
These defaults, as well as the default IdleTimeout (used on the server independent from the cookie), can be
overridden when configuring Session by using SessionOptions as shown here:
services.AddSession(options =>
{
options.CookieName = ".AdventureWorks.Session";
options.IdleTimeout = TimeSpan.FromSeconds(10);
});

The IdleTimeout is used by the server to determine how long a session can be idle before its contents are aban-
doned. Each request made to the site that passes through the Session middleware (regardless of whether Session is

1.4. Fundamentals 203


ASP.NET 5 Documentation, Release

read from or written to within that middleware) will reset the timeout. Note that this is independent of the cookie’s
expiration.

Note: Session is non-locking, so if two requests both attempt to modify the contents of session, the last one will
win. Further, Session is implemented as a coherent session, which means that all of the contents are stored together.
This means that if two requests are modifying different parts of the session (different keys), they may still impact each
other.

ISession

Once session is installed and configured, you refer to it via HttpContext, which exposes a property called Session
of type ISession. You can use this interface to get and set values in Session, as byte[].
public interface ISession
{
Task LoadAsync();
Task CommitAsync();
bool TryGetValue(string key, out byte[] value);
void Set(string key, byte[] value);
void Remove(string key);
void Clear();
IEnumerable<string> Keys { get; }
}

Because‘‘Session‘‘ is built on top of IDistributedCache, you must always serialize the object instances being
stored. Thus, the interface works with byte[] not simply object. However, there are extension methods that make
working with simple types such as String and Int32 easier, as well as making it easier to get a byte[] value from
session.
// session extension usage examples
context.Session.SetInt32("key1", 123);
int? val = context.Session.GetInt32("key1");
context.Session.SetString("key2", "value");
string stringVal = context.Session.GetString("key2");
byte[] result = context.Session.Get("key3");

If you’re storing more complex objects, you will need to serialize the object to a byte[] in order to store them, and
then deserialize them from byte[] when retrieving them.

A Working Sample Using Session

The associated sample application demonstrates how to work with Session, including storing and retrieving simple
types as well as custom objects. In order to see what happens when session expires, the sample has configured
sessions to last just 10 seconds:
1 public void ConfigureServices(IServiceCollection services)
2 {
3 services.AddCaching();
4

5 services.AddSession(options =>
6 {
7 options.IdleTimeout = TimeSpan.FromSeconds(10);
8 });
9 }

204 Chapter 1. Topics


ASP.NET 5 Documentation, Release

When you first navigate to the web server, it displays a screen indicating that no session has yet been established:

This default behavior is produced by the following middleware in Startup.cs, which runs when requests are made that
do not already have an established session (note the highlighted sections):
1 // main catchall middleware
2 app.Run(async context =>
3 {
4 RequestEntryCollection collection = GetOrCreateEntries(context);
5

6 if (collection.TotalCount() == 0)
7 {
8 await context.Response.WriteAsync("<html><body>");
9 await context.Response.WriteAsync("Your session has not been established.<br>");
10 await context.Response.WriteAsync(DateTime.Now.ToString() + "<br>");
11 await context.Response.WriteAsync("<a href=\"/session\">Establish session</a>.<br>");
12 }
13 else
14 {
15 collection.RecordRequest(context.Request.PathBase + context.Request.Path);
16 SaveEntries(context, collection);
17

18 // Note: it's best to consistently perform all session access before writing anything to resp
19 await context.Response.WriteAsync("<html><body>");
20 await context.Response.WriteAsync("Session Established At: " + context.Session.GetString("Sta
21 foreach (var entry in collection.Entries)
22 {
23 await context.Response.WriteAsync("Request: " + entry.Path + " was requested " + entry.Co
24 }
25

26 await context.Response.WriteAsync("Your session was located, you've visited the site this man
27 }
28 await context.Response.WriteAsync("<a href=\"/untracked\">Visit untracked part of application</a>
29 await context.Response.WriteAsync("</body></html>");

GetOrCreateEntries is a helper method that will retrieve a RequestEntryCollection instance from


Session if it exists; otherwise, it creates the empty collection and returns that. The collection holds
RequestEntry instances, which keep track of the different requests the user has made during the current session,
and how many requests they’ve made for each path.
1 public class RequestEntry
2 {
3 public string Path { get; set; }
4 public int Count { get; set; }
5 }

1.4. Fundamentals 205


ASP.NET 5 Documentation, Release

1 public class RequestEntryCollection


2 {
3 public List<RequestEntry> Entries { get; set; } = new List<RequestEntry>();
4

5 public void RecordRequest(string requestPath)


6 {
7 var existingEntry = Entries.FirstOrDefault(e => e.Path == requestPath);
8 if (existingEntry != null) { existingEntry.Count++; return; }
9

10 var newEntry = new RequestEntry()


11 {
12 Path = requestPath,
13 Count = 1
14 };
15 Entries.Add(newEntry);
16 }
17

18 public int TotalCount()


19 {
20 return Entries.Sum(e => e.Count);
21 }
22 }

Note: The types that are to be stored in session must be marked with [Serializable].

Fetching the current instance of RequestEntryCollection is done via the GetOrCreateEntries helper
method:
1 private RequestEntryCollection GetOrCreateEntries(HttpContext context)
2 {
3 RequestEntryCollection collection = null;
4 byte[] requestEntriesBytes = context.Session.Get("RequestEntries");
5

6 if (requestEntriesBytes != null && requestEntriesBytes.Length > 0)


7 {
8 string json = System.Text.Encoding.UTF8.GetString(requestEntriesBytes);
9 return JsonConvert.DeserializeObject<RequestEntryCollection>(json);
10 }
11 if (collection == null)
12 {
13 collection = new RequestEntryCollection();
14 }
15 return collection;
16 }

When the entry for the object exists in Session, it is retrieved as a byte[] type, and then deserialized using a
MemoryStream and a BinaryFormatter, as shown above. If the object isn’t in Session, the method returns a
new instance of the RequestEntryCollection.
In the browser, clicking the Establish session hyperlink makes a request to the path “/session”, and returns this result:

206 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Refreshing the page results in the count incrementing; returning to the root of the site (after making a few more
requests) results in this display, summarizing all of the requests that were made during the current session:

Establishing the session is done in the middleware that handles requests to “/session”:
1 // establish session
2 app.Map("/session", subApp =>
3 {
4 subApp.Run(async context =>
5 {
6 // uncomment the following line and delete session coookie to generate an error due to sessio
7 // await context.Response.WriteAsync("some content");
8 RequestEntryCollection collection = GetOrCreateEntries(context);
9 collection.RecordRequest(context.Request.PathBase + context.Request.Path);
10 SaveEntries(context, collection);
11 if (context.Session.GetString("StartTime") == null)
12 {
13 context.Session.SetString("StartTime", DateTime.Now.ToString());
14 }
15 await context.Response.WriteAsync("<html><body>");
16 await context.Response.WriteAsync($"Counting: You have made {collection.TotalCount()} request
17 await context.Response.WriteAsync("</body></html>");
18

19 });
20 });

Requests to this path will get or create a RequestEntryCollection, will add the current path to it, and then will
store it in session using the helper method SaveEntries, shown below:
1 private void SaveEntries(HttpContext context, RequestEntryCollection collection)
2 {

1.4. Fundamentals 207


ASP.NET 5 Documentation, Release

3 string json = JsonConvert.SerializeObject(collection);


4 byte[] serializedResult = System.Text.Encoding.UTF8.GetBytes(json);
5

6 context.Session.Set("RequestEntries", serializedResult);
7 }

SaveEntries demonstrates how to serialize a custom object into a byte[] for storage in Session using a
MemoryStream and a BinaryFormatter.
The sample includes one more piece of middleware worth mentioning, which is mapped to the “/untracked” path. You
can see its configuration here:
1 // example middleware that does not reference session at all and is configured before app.UseSession(
2 app.Map("/untracked", subApp =>
3 {
4 subApp.Run(async context =>
5 {
6 await context.Response.WriteAsync("<html><body>");
7 await context.Response.WriteAsync("Requested at: " + DateTime.Now.ToString() + "<br>");
8 await context.Response.WriteAsync("This part of the application isn't referencing Session...<
9 await context.Response.WriteAsync("</body></html>");
10 });
11 });
12

13 app.UseSession();

Note that this middleware is configured before the call to app.UseSession() is made (on line 13). Thus, the
Session feature is not available to this middleware, and requests made to it do not reset the session IdleTimeout.
You can confirm this behavior in the sample application by refreshing the untracked path several times within 10
seconds, and then return to the application root. You will find that your session has expired, despite no more than 10
seconds having passed between your requests to the application.

1.4.14 Servers

By Steve Smith
ASP.NET Core is completely decoupled from the web server environment that hosts the application. ASP.NET Core
supports hosting in IIS and IIS Express, and self-hosting scenarios using the Kestrel and WebListener HTTP servers.
Additionally, developers and third party software vendors can create custom servers to host their ASP.NET Core apps.

Sections:
• Servers and commands
• Supported Features by Server
• IIS and IIS Express
• WebListener
• Kestrel
• Choosing a server
• Custom Servers
• Additional Reading

View or download sample code

208 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Servers and commands

ASP.NET Core was designed to decouple web applications from the underlying HTTP server. Traditionally, ASP.NET
apps have been windows-only hosted on Internet Information Server (IIS). The recommended way to run ASP.NET
Core applications on Windows is using IIS as a reverse-proxy server. The HttpPlatformHandler module in IIS manages
and proxies requests to an HTTP server hosted out-of-process. ASP.NET Core ships with two different HTTP servers:
• Microsoft.AspNet.Server.WebListener (AKA WebListener, Windows-only)
• Microsoft.AspNet.Server.Kestrel (AKA Kestrel, cross-platform)
ASP.NET Core does not directly listen for requests, but instead relies on the HTTP server implementation to surface
the request to the application as a set of feature interfaces composed into an HttpContext. While WebListener is
Windows-only, Kestrel is designed to run cross-platform. You can configure your application to be hosted by any or
all of these servers by specifying commands in your project.json file. You can even specify an application entry point
for your application, and run it as an executable (using dotnet run) rather than hosting it in a separate process.
The default web host for ASP.NET apps developed using Visual Studio is IIS Express functioning as a reverse proxy
server for Kestrel. The “Microsoft.AspNet.Server.Kestrel” and “Microsoft.AspNet.IISPlatformHandler” dependencies
are included in project.json by default, even with the Empty web site template. Visual Studio provides support for
multiple profiles, associated with IIS Express and any other commands defined in project.json. You can manage
these profiles and their settings in the Debug tab of your web application project’s Properties menu or from the
launchSettings.json file.

Note: IIS doesn’t support commands. Visual Studio launches IIS Express and loads the application with the selected
profile.

1.4. Fundamentals 209


ASP.NET 5 Documentation, Release

The sample project for this article is configured to support each server option in the project.json file:

Listing 1.6: project.json (truncated)


1 {
2 "webroot": "wwwroot",
3 "version": "1.0.0-*",
4

5 "dependencies": {
6 "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
7 "Microsoft.AspNet.Server.WebListener": "1.0.0-rc1-final"
8 },
9

10 "commands": {
11 "run": "run server.urls=http://localhost:5003",
12 "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.Kestrel --server.urls http://lo
13 "weblistener": "Microsoft.AspNet.Hosting --server WebListener --server.urls http://localhost:5004
14 },
15

16 "frameworks": {
17 "dnx451": { },

The run command will launch the application from the void main method. The run command configures and
starts an instance of Kestrel.

Supported Features by Server

ASP.NET defines a number of Request Features. The following table lists the WebListener and Kestrel support for
request features.
Feature WebListener Kestrel
IHttpRequestFeature Yes Yes
IHttpResponseFeature Yes Yes
IHttpAuthenticationFeature Yes No
IHttpUpgradeFeature Yes (with limits) Yes
IHttpBufferingFeature Yes No
IHttpConnectionFeature Yes Yes
IHttpRequestLifetimeFeature Yes Yes
IHttpSendFileFeature Yes No
IHttpWebSocketFeature No* No*
IRequestIdentifierFeature Yes No
ITlsConnectionFeature Yes Yes
ITlsTokenBindingFeature Yes No

Configuration options

You can provide configuration options (by command line parameters or a configuration file) that are read on server
startup.
The Microsoft.AspNet.Hosting command supports server parameters (such as Kestrel or WebListener)
and a server.urls configuration key. The server.urls configuration key is a semicolon-separated list of URL
prefixes that the server should handle.
The project.json file shown above demonstrates how to pass the server.urls parameter directly:

210 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Listing 1.7: program.cs


1 using System;
2 using System.Threading.Tasks;
3 using Microsoft.AspNet.Hosting;
4 using Microsoft.Extensions.Configuration;
5 using Microsoft.AspNet.Builder;
6 using Microsoft.Extensions.Logging;
7 using Microsoft.AspNet.Server.Kestrel;
8

9 namespace ServersDemo
10 {
11 /// <summary>
12 /// This demonstrates how the application can be launched in a console application.
13 /// Executing the "dnx run" command in the application folder will run this app.
14 /// </summary>
15 public class Program
16 {
17 private readonly IServiceProvider _serviceProvider;
18

19 public Program(IServiceProvider serviceProvider)


20 {
21 _serviceProvider = serviceProvider;
22 }
23

24 public Task<int> Main(string[] args)


25 {
26 //Add command line configuration source to read command line parameters.
27 var builder = new ConfigurationBuilder();
28 builder.AddCommandLine(args);
29 var config = builder.Build();
30

31 using (new WebHostBuilder(config)


32 .UseServer("Microsoft.AspNet.Server.Kestrel")
33 .Build()
34 .Start())
35 {
36 Console.WriteLine("Started the server..");
37 Console.WriteLine("Press any key to stop the server");
38 Console.ReadLine();
39 }
40 return Task.FromResult(0);
41 }
42 }
43 }

1.4. Fundamentals 211


ASP.NET 5 Documentation, Release

"web": "Microsoft.AspNet.Kestrel --server.urls http://localhost:5004"

Alternately, a JSON configuration file can be used,


"kestrel": "Microsoft.AspNet.Hosting"

The hosting.json can include the settings the server will use (including the server parameter, as well):
{
"server": "Microsoft.AspNet.Server.Kestrel",
"server.urls": "http://localhost:5004/"
}

Programmatic configuration

The server hosting the application can be referenced programmatically via the IApplicationBuilder interface, available
in the Configure method in Startup. IApplicationBuilder exposes Server Features of type IFeatureCollection.
IServerAddressesFeature only expose a Addresses property, but different server implementations may
expose additional functionality. For instance, WebListener exposes AuthenticationManager that can be used
to configure the server’s authentication:
1 public void Configure(IApplicationBuilder app, IApplicationLifetime lifetime, ILoggerFactory loggerFa
2 {
3 var webListenerInfo = app.ServerFeatures.Get<WebListener>();
4 if (webListenerInfo != null)
5 {
6 webListenerInfo.AuthenticationManager.AuthenticationSchemes =
7 AuthenticationSchemes.AllowAnonymous;
8 }
9

10 var serverAddress = app.ServerFeatures.Get<IServerAddressesFeature>()?.Addresses.FirstOrDefault()


11

12 app.Run(async (context) =>


13 {
14 var message = String.Format("Hello World from {0}",
15 serverAddress);
16 await context.Response.WriteAsync(message);
17 });
18 }

IIS and IIS Express

IIS is the most feature rich server, and includes IIS management functionality and access to other IIS modules. Hosting
ASP.NET Core no longer uses the System.Web infrastructure used by prior versions of ASP.NET.

HTTPPlatformHandler

In ASP.NET Core on Windows, the web application is hosted by an external process outside of IIS. The HTTP Platform
Handler is an IIS 7.5+ module which is responsible for process management of HTTP listeners and used to proxy
requests to the processes that it manages.

212 Chapter 1. Topics


ASP.NET 5 Documentation, Release

WebListener

WebListener is a Windows-only HTTP server for ASP.NET Core. It runs directly on the Http.Sys kernel driver, and
has very little overhead.
You can add support for WebListener to your ASP.NET application by adding the “Mi-
crosoft.AspNet.Server.WebListener” dependency in project.json and the following command:
"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://lo

Kestrel

Kestrel is a cross-platform web server based on libuv, a cross-platform asynchronous I/O library. You add sup-
port for Kestrel by including Microsoft.AspNet.Server.Kestrel in your project’s dependencies listed in
project.json.
Learn more about working with Kestrel to create Your First ASP.NET Core Application on a Mac Using Visual Studio
Code.

Choosing a server

If you intend to deploy your application on a Windows server, you should run IIS as a reverse proxy server that
manages and proxies requests to Kestrel. If deploying on Linux, you should run a comparable reverse proxy server
such as Apache or Nginx to proxy requests to Kestrel.
For self-hosting scenarios, such as running in Service Fabric, we recommend using Kestrel without IIS. However, if
you require Windows Authentication in a self-hosting scenario, you should choose WebListener.

Custom Servers

You can create your own server in which to host ASP.NET apps, or use other open source servers. When implementing
your own server, you’re free to implement just the feature interfaces your application needs, though at a minimum you
must support IHttpRequestFeature and IHttpResponseFeature.
Since Kestrel is open source, it makes an excellent starting point if you need to implement your own custom server.
Like all of ASP.NET Core, you’re welcome to contribute any improvements you make back to the project.
Kestrel currently supports a limited number of feature interfaces, but additional features will be added in the future.

Additional Reading

• Request Features

1.4.15 Request Features

By Steve Smith
Individual web server features related to how HTTP requests and responses are handled have been factored into
separate interfaces. These abstractions are used by individual server implementations and middleware to create and
modify the application’s hosting pipeline.

1.4. Fundamentals 213


ASP.NET 5 Documentation, Release

Sections:
• Feature interfaces
• Feature collections
• Middleware and request features
• Summary
• Additional Resources

Feature interfaces

ASP.NET Core defines a number of HTTP feature interfaces, which are used by servers to identify which features they
support. The most basic features of a web server are the ability to handle requests and return responses, as defined by
the following feature interfaces:
IHttpRequestFeature Defines the structure of an HTTP request, including the protocol, path, query string, headers,
and body.
IHttpResponseFeature Defines the structure of an HTTP response, including the status code, headers, and body of
the response.
IHttpAuthenticationFeature Defines support for identifying users based on a ClaimsPrincipal and specifying
an authentication handler.
IHttpUpgradeFeature Defines support for HTTP Upgrades, which allow the client to specify which additional pro-
tocols it would like to use if the server wishes to switch protocols.
IHttpBufferingFeature Defines methods for disabling buffering of requests and/or responses.
IHttpConnectionFeature Defines properties for local and remote addresses and ports.
IHttpRequestLifetimeFeature Defines support for aborting connections, or detecting if a request has been termi-
nated prematurely, such as by a client disconnect.
IHttpSendFileFeature Defines a method for sending files asynchronously.
IHttpWebSocketFeature Defines an API for supporting web sockets.
IHttpRequestIdentifierFeature Adds a property that can be implemented to uniquely identify requests.
ISessionFeature Defines ISessionFactory and ISession abstractions for supporting user sessions.
ITlsConnectionFeature Defines an API for retrieving client certificates.
ITlsTokenBindingFeature Defines methods for working with TLS token binding parameters.

Note: ISessionFeature is not a server feature, but is implemented by the SessionMiddleware (see Man-
aging Application State).

Feature collections

The HttpContext.Features property provides an interface for getting and setting the available HTTP features for the
current request. Since the feature collection is mutable even within the context of a request middleware can be used to
modify the collection and add support for additional features.

214 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Middleware and request features

While servers are responsible for creating the feature collection, middleware can both add to this collection and con-
sume features from the collection. For example, the StaticFileMiddleware accesses the IHttpSendFileFeature
feature. If the feature exists, it is used to send the requested static file from its physical path. Otherwise, a much slower
workaround method is used to send the file. When available, the IHttpSendFileFeature allows the operating
system to open the file and perform a direct kernel mode copy to the network card.
Additionally, middleware can add to the feature collection established by the server. Existing features can even be
replaced by middleware, allowing the middleware to augment the functionality of the server. Features added to the col-
lection are available immediately to other middleware or the underlying application itself later in the request pipeline.

Note: Use the FeatureCollectionExtensions to easily get and set features on the HttpContext.

By combining custom server implementations and specific middleware enhancements, the precise set of features an
application requires can be constructed. This allows missing features to be added without requiring a change in
server, and ensures only the minimal amount of features are exposed, thus limiting attack surface area and improving
performance.

Summary

Feature interfaces define specific HTTP features that a given request may support. Servers define collections of
features, and the initial set of features supported by that server, but middleware can be used to enhance these features.

Additional Resources

• Servers
• Middleware
• OWIN

1.4.16 OWIN

By Steve Smith
ASP.NET Core supports OWIN, the Open Web Interface for .NET, which allows web applications to be decoupled
from web servers. In addition, OWIN defines a standard way for middleware to be used in a pipeline to handle individ-
ual requests and associated responses. ASP.NET Core applications and middleware can interoperate with OWIN-based
applications, servers, and middleware.

Sections:
• Running OWIN middleware in the ASP.NET pipeline
• Using ASP.NET Hosting on an OWIN-based server
• Run ASP.NET Core on an OWIN-based server and use its WebSockets support
• OWIN keys
• Summary
• Additional Resources

View or download sample code

1.4. Fundamentals 215


ASP.NET 5 Documentation, Release

Running OWIN middleware in the ASP.NET pipeline

ASP.NET Core’s OWIN support is deployed as part of the Microsoft.AspNet.Owin package. You can import
OWIN support into your project by adding this package as a dependency in your project.json file, as shown here:
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
"Microsoft.AspNet.Owin": "1.0.0-rc1-final"
},

OWIN middleware conform to the OWIN specification, which defines a Properties IDictionary<string,
object> interface that must be used, and also requires certain keys be set (such as owin.ResponseBody). We
can construct a very simple example of middleware that follows the OWIN specification to display “Hello World”, as
shown here:
public Task OwinHello(IDictionary<string, object> environment)
{
string responseText = "Hello World via OWIN";
byte[] responseBytes = Encoding.UTF8.GetBytes(responseText);

// OWIN Environment Keys: http://owin.org/spec/owin-1.0.0.html


var responseStream = (Stream)environment["owin.ResponseBody"];
var responseHeaders = (IDictionary<string, string[]>)environment["owin.ResponseHeaders"];

responseHeaders["Content-Length"] = new string[] { responseBytes.Length.ToString(CultureInfo.Inva


responseHeaders["Content-Type"] = new string[] { "text/plain" };

return responseStream.WriteAsync(responseBytes, 0, responseBytes.Length);


}

In the above example, notice that the method returns a Task and accepts an IDictionary<string, object>
as required by OWIN. Within the method, this parameter is used to retrieve the owin.ResponseBody and
owin.ResponseHeaders objects from the environment dictionary. Once the headers are set appropriately for
the content being returned, a task representing the asynchronous write to the response stream is returned.
Adding OWIN middleware to the ASP.NET pipeline is most easily done using the UseOwin extension method. Given
the OwinHello method shown above, adding it to the pipeline is a simple matter:
public void Configure(IApplicationBuilder app)
{
app.UseOwin(pipeline =>
{
pipeline(next => OwinHello);
});
}

You can of course configure other actions to take place within the OWIN pipeline. Remember that response headers
should only be modified prior to the first write to the response stream, so configure your pipeline accordingly.

Note: Multiple calls to UseOwin is discouraged for performance reasons. OWIN components will operate best if
grouped together.

app.UseOwin(pipeline =>
{
pipeline(next =>
{
// do something before

216 Chapter 1. Topics


ASP.NET 5 Documentation, Release

return OwinHello;
// do something after
});
});

Note: The OWIN support in ASP.NET Core is an evolution of the work that was done for the Katana project. Katana’s
IAppBuilder component has been replaced by IApplicationBuilder, but if you have existing Katana-based
middleware, you can use it within your ASP.NET Core application through the use of a bridge, as shown in the
Owin.IAppBuilderBridge example on GitHub.

Using ASP.NET Hosting on an OWIN-based server

OWIN-based servers can host ASP.NET applications, since ASP.NET conforms to the OWIN specification. One such
server is Nowin, a .NET OWIN web server. In the sample for this article, I’ve included a very simple project that
references Nowin and uses it to create a simple server capable of self-hosting ASP.NET Core.
1 using System;
2 using System.Collections.Generic;
3 using System.Net;
4 using System.Threading.Tasks;
5 using Microsoft.AspNet.Hosting.Server;
6 using Microsoft.AspNet.Owin;
7 using Microsoft.Extensions.Configuration;
8 using Microsoft.AspNet.Http.Features;
9 using Nowin;
10

11 namespace NowinSample
12 {
13 public class NowinServerFactory : IServerFactory
14 {
15 private Func<IFeatureCollection, Task> _callback;
16

17 private Task HandleRequest(IDictionary<string, object> env)


18 {
19 return _callback(new FeatureCollection(new OwinFeatureCollection(env)));
20 }
21

22 public IFeatureCollection Initialize(IConfiguration configuration)


23 {
24 var builder = ServerBuilder.New()
25 .SetAddress(IPAddress.Any)
26 .SetPort(5000)
27 .SetOwinApp(HandleRequest);
28

29 var serverFeatures = new FeatureCollection();


30 serverFeatures.Set<INowinServerInformation>(new NowinServerInformation(builder));
31 return serverFeatures;
32 }
33

34 public IDisposable Start(IFeatureCollection serverFeatures,


35 Func<IFeatureCollection, Task> application)
36 {
37 var information = serverFeatures.Get<INowinServerInformation>();
38 _callback = application;
39 INowinServer server = information.Builder.Build();
40 server.Start();

1.4. Fundamentals 217


ASP.NET 5 Documentation, Release

41 return server;
42 }
43

44 private class NowinServerInformation : INowinServerInformation


45 {
46 public NowinServerInformation(ServerBuilder builder)
47 {
48 Builder = builder;
49 }
50

51 public ServerBuilder Builder { get; private set; }


52

53 public string Name


54 {
55 get
56 {
57 return "Nowin";
58 }
59 }
60 }
61 }
62 }

IServerFactory is an interface that requires an Initialize and a Start method. Initialize must return an instance of
IFeatureCollection, which we populate with a INowinServerInformation that includes the server’s name (the
specific implementation may provide additional functionality). In this example, the NowinServerInformation
class is defined as a private class within the factory, and is returned by Initialize as required.
Initialize is responsible for configuring the server, which in this case is done through a series of fluent API calls
that hard code the server to listen for requests (to any IP address) on port 5000. Note that the final line of the fluent con-
figuration of the builder variable specifies that requests will be handled by the private method HandleRequest.
Start is called after Initialize and accepts the the IFeatureCollection created by Initialize, and a callback
of type Func<IFeatureCollection, Task>. This callback is assigned to a local field and is ultimately called
on each request from within the private HandleRequest method (which was wired up in Initialize).
With this in place, all that’s required to run an ASP.NET application using this custom server is the following command
in project.json:
1 {
2 "version": "1.0.0-*",
3 "compilationOptions": {
4 "emitEntryPoint": true
5 },
6

7 "dependencies": {
8 "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
9 "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
10 "Microsoft.AspNet.Owin": "1.0.0-rc1-final",
11 "Nowin": "0.22.0"
12 },
13

14 "commands": {
15 "web": "Microsoft.AspNet.Hosting --server NowinSample"
16 },

When run, this command will search for a package called “NowinSample” that contains an implementation of
IServerFactory. If it finds one, it will initialize and start the server as detailed above. Learn more about the
built-in ASP.NET Servers.

218 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Run ASP.NET Core on an OWIN-based server and use its WebSockets support

Another example of how OWIN-based servers’ features can be leveraged by ASP.NET Core is access to features like
WebSockets. The .NET OWIN web server used in the previous example has support for Web Sockets built in, which
can be leveraged by an ASP.NET Core application. The example below shows a simple web application that supports
Web Sockets and simply echos back anything sent to the server via WebSockets.
1 public class Startup
2 {
3 public void Configure(IApplicationBuilder app)
4 {
5 app.Use(async (context, next) =>
6 {
7 if (context.WebSockets.IsWebSocketRequest)
8 {
9 WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
10 await EchoWebSocket(webSocket);
11 }
12 else
13 {
14 await next();
15 }
16 });
17

18 app.Run(context =>
19 {
20 return context.Response.WriteAsync("Hello World");
21 });
22 }
23

24 private async Task EchoWebSocket(WebSocket webSocket)


25 {
26 byte[] buffer = new byte[1024];
27 WebSocketReceiveResult received = await webSocket.ReceiveAsync(
28 new ArraySegment<byte>(buffer), CancellationToken.None);
29

30 while (!webSocket.CloseStatus.HasValue)
31 {
32 // Echo anything we receive
33 await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count),
34 received.MessageType, received.EndOfMessage, CancellationToken.None);
35

36 received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer),


37 CancellationToken.None);
38 }
39

40 await webSocket.CloseAsync(webSocket.CloseStatus.Value,
41 webSocket.CloseStatusDescription, CancellationToken.None);
42 }
43

44 // Entry point for the application.


45 public static void Main(string[] args) => WebApplication.Run<Startup>(args);
46 }
47 }

This sample is configured using the same NowinServerFactory as the previous one - the only difference is in how
the application is configured in its Configure method. A simple test using a simple websocket client demonstrates
that the application works as expected:

1.4. Fundamentals 219


ASP.NET 5 Documentation, Release

OWIN keys

OWIN depends heavily on an IDictionary<string,object> used to communicate information throughout


an HTTP Request/Response exchange. ASP.NET Core implements all of the required and optional keys outlined in
the OWIN specification, as well as some of its own. Note that any keys not required in the OWIN specification are
optional and may only be used in some scenarios. When working with OWIN keys, it’s a good idea to review the list
of OWIN Key Guidelines and Common Keys

Request Data (OWIN v1.0.0)

Key Value (type) Description


owin.RequestScheme String
owin.RequestMethod String
owin.RequestPathBase String
owin.RequestPath String
owin.RequestQueryString String
owin.RequestProtocol String
owin.RequestHeaders IDictionary<string,string[]>
owin.RequestBody Stream

Request Data (OWIN v1.1.0)

Key Value (type) Description


owin.RequestId String Optional

220 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Response Data (OWIN v1.0.0)

Key Value (type) Description


owin.ResponseStatusCode int Optional
owin.ResponseReasonPhrase String Optional
owin.ResponseHeaders IDictionary<string,string[]>
owin.ResponseBody Stream

Other Data (OWIN v1.0.0)

Key Value (type) Description


owin.CallCancelled CancellationToken
owin.Version String

Common Keys

Key Value (type) Description


ssl.ClientCertificate X509Certificate
ssl.LoadClientCertAsync Func<Task>
server.RemoteIpAddress String
server.RemotePort String
server.LocalIpAddress String
server.LocalPort String
server.IsLocal bool
server.OnSendingHeaders Action<Action<object>,object>

SendFiles v0.3.0

Key Value (type) Description


sendfile.SendAsync See delegate signature Per Request

Opaque v0.3.0

Key Value (type) Description


opaque.Version String
opaque.Upgrade OpaqueUpgrade See delegate signature
opaque.Stream Stream
opaque.CallCancelled CancellationToken

1.4. Fundamentals 221


ASP.NET 5 Documentation, Release

WebSocket v0.3.0

Key Value (type) Description


websocket.Version String
websocket.Accept WebSocketAccept See delegate signature.
websocket.AcceptAlt Non-spec
websocket.SubProtocol String See RFC6455 Section 4.2.2 Step 5.5
websocket.SendAsync WebSocketSendAsync See delegate signature.
websocket.ReceiveAsync WebSocketReceiveAsync See delegate signature.
websocket.CloseAsync WebSocketCloseAsync See delegate signature.
websocket.CallCancelled CancellationToken
websocket.ClientCloseStatus int Optional
websocket.ClientCloseDescription String Optional

Summary

ASP.NET Core has built-in support for the OWIN specification, providing compatibility to run ASP.NET Core appli-
cations within OWIN-based servers as well as supporting OWIN-based middleware within ASP.NET Core servers.

Additional Resources

• Middleware
• Servers

1.5 MVC

1.5.1 Overview of ASP.NET MVC

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

1.5.2 Models

Model Binding

By Rachel Appel

222 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Sections:
• Introduction to model binding
• How model binding works
• Customize model binding behavior with attributes
• Binding formatted data from the request body

Introduction to model binding

Model binding in MVC maps data from HTTP requests to action method parameters. The parameters may be simple
types such as strings, integers, or floats, or they may be complex types. This is a great feature of MVC because
mapping incoming data to a counterpart is an often repeated scenario, regardless of size or complexity of the data.
MVC solves this problem by abstracting binding away so developers don’t have to keep rewriting a slightly different
version of that same code in every app. Writing your own text to type converter code is tedious, and error prone.

How model binding works

When MVC receives an HTTP request, it routes it to a specific action method of a controller. It determines which
action method to run based on what is in the route data, then it binds values from the HTTP request to that action
method’s parameters. For example, consider the following URL:
http://contoso.com/movies/edit/2
Since the route template looks like this, {controller=Home}/{action=Index}/{id?}, movies/edit/2
routes to the Movies controller, and its Edit action method. It also accepts an optional parameter called id. The
code for the action method should look something like this:
1 public IActionResult Edit(int? id)

Note: The strings in the URL route are not case sensitive.

MVC will try to bind request data to the action parameters by name. MVC will look for values for each parameter
using the parameter name and the names of its public settable properties. In the above example, the only action
parameter is named id, which MVC binds to the value with the same name in the route values. In addition to route
values MVC will bind data from various parts of the request and it does so in a set order. Below is a list of the data
sources in the order that model binding looks through them:
1. Form values: These are form values that go in the HTTP request using the POST method. (including jQuery
POST requests).
2. Route values: The set of route values provided by routing.
3. Query strings: The query string part of the URI.

Note: Form values, route data, and query strings are all stored as name-value pairs.

Since model binding asked for a key named id and there is nothing named id in the form values, it moved on to the
route values looking for that key. In our example, it’s a match. Binding happens, and the value is converted to the
integer 2. The same request using Edit(string id) would convert to the string “2”.
So far the example uses simple types. In MVC simple types are any .NET primitive type or type with a string type
converter. If the action method’s parameter were a class such as the Movie type, which contains both simple and com-
plex types as properties, MVC’s model binding will still handle it nicely. It uses reflection and recursion to traverse the

1.5. MVC 223


ASP.NET 5 Documentation, Release

properties of complex types looking for matches. Model binding looks for the pattern parameter_name.property_name
to bind values to properties. If it doesn’t find matching values of this form, it will attempt to bind using just the prop-
erty name. For those types such as Collection types, model binding looks for matches to parameter_name[index]
or just [index]. Model binding treats Dictionary types similarly, asking for parameter_name[key] or just [key], as
long as they keys are simple types. Keys that are supported match the field names HTML and tag helpers generated
for the same model type. This enables round-tripping values so that the form fields remain filled with the user’s input
for their convenience, for example, when bound data from a create or edit did not pass validation.
In order for binding to happen the class must have a public default constructor and member to be bound must be
public writable properties. When model binding happens the class will only be instantiated using the public default
constructor, then the properties can be set.
When a parameter is bound, model binding stops looking for values with that name and it moves on to bind the next
parameter. If binding fails, MVC does not throw an error. You can query for model state errors by checking the
ModelState.IsValid property.

Note: Each entry in the controller’s ModelState property is a ModelStateEntry containing an Errors
property. It’s rarely necessary to query this collection yourself. Use ModelState.IsValid instead.

Additionally, there are some special data types that MVC must consider when performing model binding:
• IFormFile, IEnumerable<IFormFile>: One or more uploaded files that are part of the HTTP request.
• CancelationToken: Used to cancel activity in asynchronous controllers.
These types can be bound to action parameters or to properties on a class type.
Once model binding is complete, validation occurs. Default model binding works great for the vast majority of
development scenarios. It is also extensible so if you have unique needs you can customize the built-in behavior.

Customize model binding behavior with attributes

MVC contains several attributes that you can use to direct its default model binding behavior to a different source.
For example, you can specify whether binding is required for a property, or if it should never happen at all by using
the [BindRequired] or [BindNever] attributes. Alternatively, you can override the default data source, and
specify the model binder’s data source. Below is a list of model binding attributes:
• [BindRequired]: This attribute adds a model state error if binding cannot occur.
• [BindNever]: Tells the model binder to never bind to this parameter.
• [FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding
source you want to apply.
• [FromServices]: This attribute uses dependency injection to bind parameters from services.
• [FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected
based on content type of the request.
• [ModelBinder]: Used to override the default model binder, binding source and name.
Attributes are very helpful tools when you need to override the default behavior of model binding.

Binding formatted data from the request body

Request data can come in a variety of formats including JSON, XML and many others. When you use the [FromBody]
attribute to indicate that you want to bind a parameter to data in the request body, MVC uses a configured set of

224 Chapter 1. Topics


ASP.NET 5 Documentation, Release

formatters to handle the request data based on its content type. By default MVC includes a JsonInputFormatter
class for handling JSON data, but you can add additional formatters for handling XML and other custom formats.

Note: The JsonInputFormatter is the default formatter and it is based off of Json.NET.

ASP.NET selects input formatters based on the Content-Type header and the type of the parameter, unless there is
an attribute applied to it specifying otherwise. If you’d like to use XML or another format you must configure it in
the Startup.cs file, but you may first have to obtain a reference to Microsoft.AspNet.Mvc.Formatters.Xml
using NuGet. Your startup code should look something like this:
1 public void ConfigureServices(IServiceCollection services)
2 {
3 services.AddMvc()
4 .AddXmlSerializerFormatters();
5 }

Code in the Startup.cs file contains a ConfigureServices method with a services argument you can use to
build up services for your ASP.NET app. In the sample, we are adding an XML formatter as a service that MVC will
provide for this app. The options argument passed into the AddMvc method allows you to add and manage filters,
formatters, and other system options from MVC upon app startup. Then apply the Consumes attribute to controller
classes or action methods to work with the format you want.

Model Validation

By Rachel Appel
In this article:

Sections
• Introduction to model validation
• Validation Attributes
• Model State
• Manual validation
• Custom validation
• Client side validation
• IClientModelValidator
• Remote validation

Introduction to model validation

Before an app stores data in a database, the app must validate the data. Data must be checked for potential security
threats, verified that it is appropriately formatted by type and size, and it must conform to your rules. Validation is
necessary although it can be redundant and tedious to implement. In MVC, validation happens on both the client and
server.
Fortunately, .NET has abstracted validation into validation attributes. These attributes contain validation code, thereby
reducing the amount of code you must write.

Validation Attributes

Validation attributes are a way to configure model validation so it’s similar conceptually to validation on fields in
database tables. This includes constraints such as assigning data types or required fields. Other types of validation

1.5. MVC 225


ASP.NET 5 Documentation, Release

include applying patterns to data to enforce business rules, such as a credit card, phone number, or email address.
Validation attributes make enforcing these requirements much simpler and easier to use.
Below is an annotated Movie model from an app that stores information about movies and TV shows. Most of the
properties are required and several string properties have length requirements. Additionally, there is a numeric range
restriction in place for the Price property from 0 to $999.99, along with a custom validation attribute.
public class Movie
{
public int Id { get; set; }

[Required]
[StringLength(100)]
public string Title { get; set; }

[Required]
[ClassicMovie(1960)]
public DateTime ReleaseDate { get; set; }

[Required]
[StringLength(1000)]
public string Description { get; set; }

[Required]
[Range(0, 999.99)]
public decimal Price { get; set; }

[Required]
public Genre Genre { get; set; }

public bool Preorder { get; set; }

[Required]
public Audience Audience { get; set; }
public List<Review> Reviews { get; set; }
}

Simply reading through the model reveals the rules about data for this app, making it easier to maintain the code.
Below are several popular built-in validation attributes:
• [CreditCard]: Validates the property has a credit card format.
• [Compare]: Validates two properties in a model match.
• [EmailAddress]: Validates the property has an email format.
• [Phone]: Validates the property has a telephone format.
• [Range]: Validates the property value falls within the given range.
• [RegularExpression]: Validates that the data matches the specified regular expression.
• [Required]: Makes a property required.
• [StringLength]: Validates that a string property has at most the given maximum length.
• [Url]: Validates the property has a URL format.
MVC supports any attribute that derives from ValidationAttribute for validation purposes. Many useful
validation attributes can be found in the System.ComponentModel.DataAnnotations namespace.
There may be instances where you need more features than built-in attributes provide. For those times, you can
create custom validation attributes by deriving from ValidationAttribute or change your model to subclass

226 Chapter 1. Topics


ASP.NET 5 Documentation, Release

IValidatableObject.

Model State

Model state represents validation errors that were submitted with HTML form values.
MVC will continue validating fields until reaches the maximum number of errors (200 by default). You can configure
this number by inserting the following code into the ConfigureServices method in the Startup.cs file:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MvcOptions>(options =>
{
options.MaxModelValidationErrors = 50;
});
}
}

Manual validation

After model binding and validation are complete, you may want to repeat parts of it. For example, a user may have
entered text in a field expecting an integer, or you may need to compute a value for a model’s property.
You may need to run validation manually. To do so, call the TryValidateModel method, as shown here:
TryValidateModel(movie);

Custom validation

Validation attributes work for most validation needs. However, some validation rules are specific to your business, as
they’re not just generic data validation such as ensuring a field is required or that it conforms to a range of values. For
these scenarios, custom validation attributes are a great solution. Creating your own custom validation attributes in
MVC is easy. Just inherit from the ValidationAttribute, and override the IsValid method. The IsValid
method accepts two parameters, the first is an object named value and the second is a ValidationContext object
named validationContext. Value refers to the actual value from the field that your custom validator is validating.
In the following sample, a business rule that states that users may not set the genre to Classic for a movie released after
1960. The [ClassicMovie] attribute checks the genre first, and if it is a classic, then it checks the release date to
see that it is later than 1960. If it is released after 1960, validation fails. The attribute accepts an integer parameter
representing the year that you can use to validate data. You can capture the value of the parameter in the attribute’s
constructor, as shown here:
public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator
{
private int _year;
public ClassicMovieAttribute(int Year)
{
_year = Year;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)


{
Movie movie = (Movie)validationContext.ObjectInstance;

1.5. MVC 227


ASP.NET 5 Documentation, Release

if (movie.Genre == Genre.Classic)
{
if (movie.ReleaseDate.Year < _year)
{
return new ValidationResult(
"Classic movies must have a release year earlier than " + this._year);

}
}
return ValidationResult.Success;
}

public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ClientModelValidationContext context)
{

The movie variable above represents a Movie object that contains the data from the form submission to validate. In
this case, the validation code checks the date and genre in the IsValid method of the ClassicMovieAttribute
class as per the rules. Upon successful validation IsValid returns a ValidationResult.Success code, and
when validation fails, a ValidationResult with an error message. When a user modifies the Genre field and
submits the form, the IsValid method of the ClassicMovieAttribute will verify whether the movie is a
classic. Like any built-in attribute, apply the ClassicMovieAttribute to a property such as ReleaseDate to
ensure validation happens, as shown in the previous code sample. Since the example works only with Movie types, a
better option is to use IValidatableObject as shown in the following paragraph.
Alternatively, this same code could be placed in the model instead by implementing the Validate method on the
IValidatableObject interface. While custom validation attributes work well for validating individual properties,
implementing IValidatableObject can be used to implement class-level validation as seen here.
public IEnumerable<ValidationResult>
Validate(ValidationContext validationContext)
{
if (Genre == Genre.Classic)
{
if (ReleaseDate.Year > _classicYear)
{
yield return new ValidationResult(
"Classic movies must have a release year earlier than " + _classicYear,
new[] { "ReleaseDate" });
}
}
}

Client side validation

Client side validation is a great convenience for users. It saves time they would otherwise spend waiting for a round
trip to the server. In business terms, even a few fractions of seconds multiplied hundreds of times each day adds up
to be a lot of time, expense, and frustration. Straightforward and immediate validation enables users to work more
efficiently and produce better quality input and output.
You must have a view with the proper JavaScript script references in place for client side validation to work as you see
here.
<script src="~/lib/jquery/jquery.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

228 Chapter 1. Topics


ASP.NET 5 Documentation, Release

MVC uses validation attributes in addition to type metadata from model properties to validate data and display any
error messages using JavaScript. When you use MVC to render form elements from a model using Tag Helpers or
HTML helpers it will add HTML 5 data- attributes in the form elements that need validation, as shown below. MVC
generates the data- attributes for both built-in and custom attributes. The data-val-required attribute below
contains an error message to display if the user doesn’t fill in the release date field, and that message displays in the
accompanying <span> element. You can display validation errors on the client using the relevant tag helpers as
shown here:
<form asp-action="Create">
<div class="form-horizontal">
<h4>Movie</h4>
<div class="form-group">
<label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ReleaseDate" class="form-control" />
<span asp-validation-for="ReleaseDate" class="text-danger"></span>
</div>
</div>
</div>
</form>

The tag helpers above render the HTML below. Notice that the data- attributes in the HTML output correspond to
the validation attributes for the ReleaseDate property.
<form action="/movies/Create" method="post">
<div class="form-horizontal">
<h4>Movie</h4>
<div class="text-danger"></div>
<div class="form-group">
<label class="col-md-2 control-label" for="ReleaseDate">ReleaseDate</label>
<div class="col-md-10">
<input class="form-control" type="datetime"
data-val="true" data-val-required="The ReleaseDate field is required."
id="ReleaseDate" name="ReleaseDate" value="" />
<span class="text-danger field-validation-valid"
data-valmsg-for="ReleaseDate" data-valmsg-replace="true"></span>
</div>
</div>
</div>
</form>

Client-side validation prevents submission until the form is valid. The Submit button runs JavaScript that either
submits the form or displays error messages.
MVC determines type attribute values based on the .NET data type of a property, possibly overridden using
[DataType] attributes. The base [DataType] attribute does no real server-side validation. Browsers choose
their own error messages and display those errors however they wish, however the jQuery Validation Unobtrusive
package can override the messages and display them consistently with others. This happens most obviously when
users apply [DataType] subclasses such as [EmailAddress].

IClientModelValidator

You may create client side logic for your custom attribute, and unobtrusive validation will execute it on the client for
you automatically as part of validation. The first step is to control what data- attributes are added by implementing the
IClientModelValidator interface as shown here:

1.5. MVC 229


ASP.NET 5 Documentation, Release

public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator


{
private int _year;
public ClassicMovieAttribute(int Year)
{
_year = Year;
}

protected override ValidationResult IsValid(object value, ValidationContext validationContext)


{
Movie movie = (Movie)validationContext.ObjectInstance;

if (movie.Genre == Genre.Classic)
{
if (movie.ReleaseDate.Year < _year)
{
return new ValidationResult(
"Classic movies must have a release year earlier than " + this._year);

}
}
return ValidationResult.Success;
}

public IEnumerable<ModelClientValidationRule>
GetClientValidationRules(ClientModelValidationContext context)
{
yield return new ModelClientValidationRule("classicmovie",
"Classic movies must have a release year earlier than " + this._year);
}
}

Attributes that implement this interface can add HTML attributes to generated fields. Examining the output
for the ReleaseDate element reveals HTML that is similar to the previous example, except now there is
a data-val-classicmovie attribute that was defined in the GetClientValidationRules method of
IClientModelValidator.
<input class="form-control" type="datetime"
data-val="true"
data-val-classicmovie="Classic movies must have a release year earlier than 1960"
data-val-required="The ReleaseDate field is required."
id="ReleaseDate" name="ReleaseDate" value="" />

Unobtrusive validation uses the data in the data- attributes to display error messages. However, jQuery doesn’t know
about rules or messages until you add them to jQuery’s validator object. This is shown in the example below that
adds a method named classicmovie containing custom client validation code to the jQuery validator object.
$(function () {
jQuery.validator.addMethod('classicmovie',
function (value, element, params) {
// custom validation code
return false;
}, '');

jQuery.validator.unobtrusive.adapters.add('classicmovie',
function (options) {
options.rules['classicmovie'] = {};
options.messages['classicmovie'] = options.message;

230 Chapter 1. Topics


ASP.NET 5 Documentation, Release

});
}(jQuery));

Now jQuery has the information to execute the custom JavaScript validation as well as the error message to display if
that validation code returns false.

Remote validation

Remote validation is a great feature to use when you need to validate data on the client against data on the server. For
example, your app may need to verify whether an email or user name is already in use, and it must query a large amount
of data to do so. Downloading large sets of data for validating one or a few fields consumes too many resources. It
may also expose sensitive information. An alternative is to make a round-trip request to validate a field.
You can implement remote validation in a two step process. First, you must annotate your model with the [Remote]
attribute. The [Remote] attribute accepts multiple overloads you can use to direct client side JavaScript to the
appropriate code to call. The example points to the VerifyEmail action method of the Users controller.
public class UserRepository : IUserRepository
{
[Remote(action: "VerifyEmail", controller: "Users")]
public string Email { get; set; }

public bool VerifyEmail()


{
// in the real world this would actually verify the email
throw new NotImplementedException();
}
}
}

The second step is putting the validation code in the corresponding action method as defined in the [Remote]
attribute. It returns a JsonResult that the client side can use to proceed or pause and display an error if needed.
public class UsersController : Controller
{
private IUserRepository userRepo;
public UsersController()
{
this.userRepo = new UserRepository();
}

[AcceptVerbs("Get", "Post")]
public IActionResult VerifyEmail(string email)
{
if (!this.userRepo.VerifyEmail())
{
return Json(data: $"Email {email} is already in use.");
}

return Json(data: true);


}

Now when users enter an email, JavaScript in the view makes a remote call to see if that email has been taken, and if
so, then displays the error message. Otherwise, the user can submit the form as usual.

1.5. MVC 231


ASP.NET 5 Documentation, Release

Formatting

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Custom Formatters

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

1.5.3 Views

Razor Syntax

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Layout

By Steve Smith
Views frequently share visual and programmatic elements. In this article, you’ll learn how to use common layouts,
share directives, and run common code before rendering views in your ASP.NET app.

Sections
• What is a Layout
• Specifying a Layout
• Importing Shared Directives
• Running Code Before Each View

232 Chapter 1. Topics


ASP.NET 5 Documentation, Release

What is a Layout

Most web apps have a common layout that provides the user with a consistent experience as they navigate from page
to page. The layout typically includes common user interface elements such as the app header, navigation or menu
elements, and footer.

Common HTML structures such as scripts and stylesheets are also frequently used by many pages within an app. All
of these shared elements may be defined in a layout file, which can then be referenced by any view used within the
app. Layouts reduce duplicate code in views, helping them follow the Don’t Repeat Yourself (DRY) principle.
By convention, the default layout for an ASP.NET app is named _Layout.cshtml. The Visual Studio ASP.NET
MVC project template includes this layout file in the Views/Shared folder:

This layout defines a top level template for views in the app. Apps do not require a layout, and apps can define more
than one layout, with different views specifying different layouts.
An example _Layout.cshtml:

1.5. MVC 233


ASP.NET 5 Documentation, Release

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - WebApplication1</title>

<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
<link rel="stylesheet" href="~/css/site.css" />
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/css/bootstrap.mi
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-te
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navb
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a asp-controller="Home" asp-action="Index" class="navbar-brand">WebApplication1</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>
@await Html.PartialAsync("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>&copy; 2016 - WebApplication1</p>
</footer>
</div>

<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>

234 Chapter 1. Topics


ASP.NET 5 Documentation, Release

<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.6/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>

@RenderSection("scripts", required: false)


</body>
</html>

Specifying a Layout

Razor views have a Layout property. Individual views specify a layout by defining this property:
@{
Layout = "_Layout";
}

The layout specified can use a full path (example: /Views/Shared/_Layout.cshtml) or a partial name (ex-
ample: _Layout). When a partial name is provided, the Razor view engine will search for the layout file using its
standard discovery process. The controller-associated folder is searched first, followed by the Shared folder. This
discovery process is identical to the one used to discover partial views.
Every layout must call RenderBody. Wherever the call to RenderBody is placed, the contents of the view will be
rendered.

Sections A layout can optionally reference one or more sections, by calling RenderSection. Sections provide a
way to organize where certain page elements should be placed. Each call to RenderSection can specify whether
that section is required or optional. Individual views specify the content to be rendered within a section using the
@section Razor syntax. If a view defines a section, it must be rendered (or an error will occur).
An example @section definition in a view:
@section Scripts {
<script type="text/javascript" src="/scripts/main.js"></script>
}

In the code above, validation scripts are added to the scripts section on a view that includes a form. Other views
in the same application might not require any additional scripts, and so wouldn’t need to define a scripts section.
Sections only flow from views. They cannot be referenced from partials, view components, or other parts of the view
system.

Importing Shared Directives

Views can use Razor directives to do many things, such as specifying namespaces or performing dependency injection.
Directives used by many views may be specified in a _ViewImports.cshtml file. The _ViewImports file
supports the following directives:
• addTagHelper
• removeTagHelper
• tagHelperPrefix
• using

1.5. MVC 235


ASP.NET 5 Documentation, Release

• model
• inherits
• inject
The file does not support other Razor features, such as functions and section definitions.
A sample _ViewImports.cshtml file:
@using WebApplication1
@using WebApplication1.Models
@using WebApplication1.Models.AccountViewModels
@using WebApplication1.Models.ManageViewModels
@using Microsoft.AspNetCore.Identity
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

The _ViewImports.cshtml file for an ASP.NET Core MVC app is typically placed in the Views folder root.
A _ViewImports.cshtml file can be placed within a controller-associated view folder, in which case it will
only be applied to views within that folder. _ViewImports files are run first at the root level, and then for a
_ViewImports file specified in the controller-associated folder, so settings specified at the root level may be over-
ridden at the folder level.
For example, if a root level _ViewImports.cshtml file specifies @model and @addTagHelper, and another
_ViewImports.cshtml file in the controller-associated folder of the view specifies a different @model and adds
another @addTagHelper, the view will have access to both tag helpers and will use the latter @model.
If multiple _ViewImports.cshtml files are run for a view, combined behavior of the directives included in the
ViewImports.cshtml files will be as follows:
• addTagHelper, remoteTagHelper: all run, in order
• tagHelperPrefix: the closest one to the view overrides any others
• model: the closest one to the view overrides any others
• inherits: the closest one to the view overrides any others
• using: all are included; duplicates are ignored
• inject: for each property, the closest one to the view overrides any others with the same property name

Running Code Before Each View

If you have code you need to run before every view, this should be placed in the _ViewStart.cshtml file. By
convention, the _ViewStart.cshtml file is located in the root of the Views folder. The statements listed in
_ViewStart.cshtml are run before every full view (not layouts, and not partial views). Like ViewImports.cshtml,
_ViewStart.cshtml is hierarchical. If a _ViewStart.cshtml file is defined in the controller-associated view
folder, it will be run after the one defined in the root of the Views folder (if any).
A sample _ViewStart.cshtml file:
@{
Layout = "_Layout";
}

The file above specifies that all views will use the _Layout.cshtml layout.

Note: Neither _ViewStart.cshtml nor _ViewImports.cshtml are placed in the /Views/Shared folder.
The app-level versions of these files should be placed directly in the /Views folder.

236 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Dynamic vs Strongly Typed Views

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Learn more about Dynamic vs Strongly Typed Views.

Working with Forms

By Rick Anderson, Dave Paquette and Jerrie Pelser


This document demonstrates working with Forms and the HTML elements commonly used on a Form. The HTML
Form element provides the primary mechanism web apps use to post back data to the server. Most of this document
describes Tag Helpers and how they can help you productively create robust HTML forms. We recommend you read
Introduction to Tag Helpers before you read this document.
In many cases, HTML Helpers provide an alternative approach to a specific Tag Helper, but it’s important to recognize
that Tag Helpers do not replace HTML Helpers and there is not a Tag Helper for each HTML Helper. When an HTML
Helper alternative exists, it is mentioned.

Sections:
• The Form Tag Helper
• The Input Tag Helper
• The Textarea Tag Helper
• The Label Tag Helper
• The Validation Tag Helpers
• The Select Tag Helper
• Additional Resources

The Form Tag Helper

The Form Tag Helper:


• Generates the HTML <FORM> action attribute value for a MVC controller action or named route
• Generates a hidden Request Verification Token to prevent cross-site request forgery (when used with the
[ValidateAntiForgeryToken] attribute in the HTTP Post action method)
• Provides the asp-route-<Parameter Name> attribute, where <Parameter Name> is added to the
route values. The routeValues parameters to Html.BeginForm and Html.BeginRouteForm provide
similar functionality.
• Has an HTML Helper alternative Html.BeginForm and Html.BeginRouteForm
Sample:

1.5. MVC 237


ASP.NET 5 Documentation, Release

<form asp-controller="Demo" asp-action="Register" method="post">


<!-- Input and Submit elements -->
</form>

The Form Tag Helper above generates the following HTML:


<form method="post" action="/Demo/Register">
<!-- Input and Submit elements -->
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The MVC runtime generates the action attribute value from the Form Tag Helper attributes asp-controller
and asp-action. The Form Tag Helper also generates a hidden Request Verification Token to prevent cross-site
request forgery (when used with the [ValidateAntiForgeryToken] attribute in the HTTP Post action method).
Protecting a pure HTML Form from cross-site request forgery is very difficult, the Form Tag Helper provides this
service for you.

Using a named route The asp-route Tag Helper attribute can also generate markup for the HTML action
attribute. An app with a route named register could use the following markup for the registration page:
<form asp-route="register" method="post">
<!-- Input and Submit elements -->
</form>

Many of the views in the Views/Account folder (generated when you create a new web app with Individual User
Accounts) contain the asp-route-returnurl attribute:
<form asp-controller="Account" asp-action="Login"
asp-route-returnurl="@ViewData["ReturnUrl"]"
method="post" class="form-horizontal" role="form">

Note With the built in templates, returnUrl is only populated automatically when you try to access
an authorized resource but are not authenticated or authorized. When you attempt an unauthorized
access, the security middleware redirects you to the login page with the returnUrl set.

The Input Tag Helper

The Input Tag Helper binds an HTML <input> element to a model expression in your razor view.
Syntax:
<input asp-for="<Expression Name>" />

The Input Tag Helper:


• Generates the id and name HTML attributes for the expression name specified in the asp-for attribute.
asp-for="Property1.Property2" is equivalent to m => m.Property1.Property2, that is the
attribute value literally is part of an expression. The name of the expression is what’s used for the asp-for
attribute value.
• Sets the HTML type attribute value based on the model type and data annotation attributes applied to the model
property
• Will not overwrite the HTML type attribute value when one is specified
• Generates HTML5 validation attributes from data annotation attributes applied to model properties
• Has an HTML Helper feature overlap with Html.TextBoxFor and Html.EditorFor. See the HTML
Helper alternatives to Input Tag Helper section for details.

238 Chapter 1. Topics


ASP.NET 5 Documentation, Release

• Provides strong typing. If the name of the property changes and you don’t update the Tag Helper you’ll get an
error similar to the following:
An error occurred during the compilation of a resource required to process
this request. Please review the following specific error details and modify
your source code appropriately.

Type expected
'RegisterViewModel' does not contain a definition for 'Email' and no
extension method 'Email' accepting a first argument of type 'RegisterViewModel'
could be found (are you missing a using directive or an assembly reference?)

The Input Tag Helper sets the HTML type attribute based on the .NET type. The following table lists some
common .NET types and generated HTML type (not every .NET type is listed).
.NET type Input Type
Bool type=”checkbox”
String type=”text”
DateTime type=”datetime”
Byte type=”number”
Int type=”number”
Single, Double type=”number”
The following table shows some common data annotations attributes that the input tag helper will map to specific input
types (not every validation attribute is listed):
Attribute Input Type
[EmailAddress] type=”email”
[Url] type=”url”
[HiddenInput] type=”hidden”
[Phone] type=”tel”
[DataType(DataType.Password)] type=”password”
[DataType(DataType.Date)] type=”date”
[DataType(DataType.Time)] type=”time”
Sample:
using System.ComponentModel.DataAnnotations;

namespace FormsTagHelper.ViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}

@model RegisterViewModel

<form asp-controller="Demo" asp-action="RegisterInput" method="post">


Email: <input asp-for="Email" /> <br />
Password: <input asp-for="Password" /><br />

1.5. MVC 239


ASP.NET 5 Documentation, Release

<button type="submit">Register</button>
</form>

The code above generates the following HTML:


<form method="post" action="/Demo/RegisterInput">
Email:
<input type="email" data-val="true"
data-val-email="The Email Address field is not a valid e-mail address."
data-val-required="The Email Address field is required."
id="Email" name="Email" value="" /> <br>
Password:
<input type="password" data-val="true"
data-val-required="The Password field is required."
id="Password" name="Password" /><br>
<button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The data annotations applied to the Email and Password properties generate metadata on the model. The Input Tag
Helper consumes the model metadata and produces HTML5 data-val-* attributes (see Model Validation). These
attributes describe the validators to attach to the input fields. This provides unobtrusive HTML5 and jQuery validation.
The unobtrusive attributes have the format data-val-rule="Error Message", where rule is the name of
the validation rule (such as data-val-required, data-val-email, data-val-maxlength, etc.) If an
error message is provided in the attribute, it is displayed as the value for the data-val-rule attribute. There are
also attributes of the form data-val-ruleName-argumentName="argumentValue" that provide additional
details about the rule, for example, data-val-maxlength-max="1024" .

HTML Helper alternatives to Input Tag Helper Html.TextBox, Html.TextBoxFor, Html.Editor


and Html.EditorFor have overlapping features with the Input Tag Helper. The Input Tag Helper will au-
tomatically set the type attribute; Html.TextBox and Html.TextBoxFor will not. Html.Editor and
Html.EditorFor handle collections, complex objects and templates; the Input Tag Helper does not. The In-
put Tag Helper, Html.EditorFor and Html.TextBoxFor are strongly typed (they use lambda expressions);
Html.TextBox and Html.Editor are not (they use expression names).

Expression names The asp-for attribute value is a ModelExpression and the right hand side of a lambda expres-
sion. Therefore, asp-for="Property1" becomes m => m.Property1 in the generated code which is why
you don’t need to prefix with Model. You can use the “@” character to start an inline expression and move before the
m.:
@{
var joe = "Joe";
}
<input asp-for="@joe" />

Generates the following:


<input type="text" id="joe" name="joe" value="Joe" />

Navigating child properties You can also navigate to child properties using the property path of the view model.
Consider a more complex model class that contains a child Address property.
public class AddressViewModel
{

240 Chapter 1. Topics


ASP.NET 5 Documentation, Release

public string AddressLine1 { get; set; }


}

public class RegisterAddressViewModel


{
public string Email { get; set; }

[DataType(DataType.Password)]
public string Password { get; set; }

public AddressViewModel Address { get; set; }


}

In the view, we bind to Address.AddressLine1:


@model RegisterAddressViewModel

<form asp-controller="Demo" asp-action="RegisterAddress" method="post">


Email: <input asp-for="Email" /> <br />
Password: <input asp-for="Password" /><br />
Address: <input asp-for="Address.AddressLine1" /><br />
<button type="submit">Register</button>
</form>

The following HTML is generated for Address.AddressLine1:


<input type="text" id="Address_AddressLine1" name="Address.AddressLine1" value="" />

Expression names and Collections Sample, a model containing an array of Colors:


public class Person
{
public List<string> Colors { get; set; }

public int Age { get; set; }


}

The action method:


public IActionResult Edit(int id, int colorIndex)
{
ViewData["Index"] = colorIndex;
return View(GetPerson(id));
}

The following Razor shows how you access a specific Color element:
@model Person
@{
var index = (int)ViewData["index"];
}

<form asp-controller="ToDo" asp-action="Edit" method="post">


@Html.EditorFor(m => m.Colors[index])
<label asp-for="Age"></label>
<input asp-for="Age" /><br />
<button type="submit">Post</button>
</form>

1.5. MVC 241


ASP.NET 5 Documentation, Release

The Views/Shared/EditorTemplates/String.cshtml template:


@model string

<label asp-for="@Model"></label>
<input asp-for="@Model" /> <br />

Sample using List<T>:


public class ToDoItem
{
public string Name { get; set; }

public bool IsDone { get; set; }

The following Razor shows how to iterate over a collection:


@model List<ToDoItem>

<form asp-controller="ToDo" asp-action="Edit" method="post">


<table>
<tr> <th>Name</th> <th>Is Done</th> </tr>

@for (int i = 0; i < Model.Count; i++)


{
<tr>
@Html.EditorFor(model => model[i])
</tr>
}

</table>
<button type="submit">Save</button>
</form>

The Views/Shared/EditorTemplates/ToDoItem.cshtml template:


@model ToDoItem

<td>
<label asp-for="@Model.Name"></label>
@Html.DisplayFor(model => model.Name)
</td>
<td>
<input asp-for="@Model.IsDone" />
</td>

@*
This template replaces the following Razor which evaluates the indexer three times.
<td>
<label asp-for="@Model[i].Name"></label>
@Html.DisplayFor(model => model[i].Name)
</td>
<td>
<input asp-for="@Model[i].IsDone" />
</td>
*@

Note Always use for (and not foreach) to iterate over a list. Evaluating an indexer in a LINQ expres-
sion can be expensive and should be minimized.

242 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Note The commented sample code above shows how you would replace the lambda expression with the
@ operator to access each ToDoItem in the list.

The Textarea Tag Helper

The Textarea Tag Helper tag helper is similar to the Input Tag Helper.
• Generates the id and name attributes, and the data validation attributes from the model for a <textarea> element.
• Provides strong typing.
• HTML Helper alternative: Html.TextAreaFor
Sample:
using System.ComponentModel.DataAnnotations;

public class DescriptionViewModel


{
[MinLength(5)]
[MaxLength(1024)]
public string Description { get; set; }
}

@model DescriptionViewModel

<form asp-controller="Demo" asp-action="RegisterTextArea" method="post">


<textarea asp-for="Description"></textarea>
<button type="submit">Test</button>
</form>

The following HTML is generated:


<form method="post" action="/Demo/RegisterTextArea">
<textarea data-val="true"
data-val-maxlength="The field Description must be a string or array type with a maximum length of
data-val-maxlength-max="1024"
data-val-minlength="The field Description must be a string or array type with a minimum length of
data-val-minlength-min="5"
id="Description" name="Description">
</textarea>
<button type="submit">Test</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The Label Tag Helper

• Generates the label caption and for attribute on a <label> element for an expression name
• HTML Helper alternative: Html.LabelFor.
The Label Tag Helper provides the following benefits over a pure HTML label element:
• You automatically get the descriptive label value from the Display attribute. The intended display name might
change over time, and the combination of Display attribute and Label Tag Helper will apply the Display
everywhere it’s used.
• Less markup in source code

1.5. MVC 243


ASP.NET 5 Documentation, Release

• Strong typing with the model property.


Sample:
using System.ComponentModel.DataAnnotations;
public class SimpleViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }
}

@model SimpleViewModel

<form asp-controller="Demo" asp-action="RegisterLabel" method="post">


<label asp-for="Email"></label>
<input asp-for="Email" /> <br />
</form>

The following HTML is generated for the <label> element:


<label for="Email">Email Address</label>

The Label Tag Helper generated the for attribute value of “Email”, which is the ID associated with the <input>
element. The Tag Helpers generate consistent id and for elements so they can be correctly associated. The caption
in this sample comes from the Display attribute. If the model didn’t contain a Display attribute, the caption would
be the property name of the expression.

The Validation Tag Helpers

There are two Validation Tag Helpers. The Validation Message Tag Helper (which displays a validation message for
a single property on your model), and the Validation Summary Tag Helper (which displays a summary of validation
errors). The Input Tag Helper adds HTML5 client side validation attributes to input elements based on data annotation
attributes on your model classes. Validation is also performed on the server. The Validation Tag Helper displays these
error messages when a validation error occurs.

The Validation Message Tag Helper


• Adds the HTML5 data-valmsg-for="property" attribute to the span element, which attaches the val-
idation error messages on the input field of the specified model property. When a client side validation error
occurs, jQuery displays the error message in the <span> element.
• Validation also takes place on the server. Clients may have JavaScript disabled and some validation can only be
done on the server side.
• HTML Helper alternative: Html.ValidationMessageFor
The Validation Message Tag Helper is used with the asp-validation-for attribute on a HTML span element.
<span asp-validation-for="Email">

The Validation Message Tag Helper will generate the following HTML:
<span class="field-validation-valid"
data-valmsg-for="Email"
data-valmsg-replace="true">

244 Chapter 1. Topics


ASP.NET 5 Documentation, Release

You generally use the Validation Message Tag Helper after an Input Tag Helper for the same property. Doing so
displays any validation error messages near the input that caused the error.
Note You must have a view with the correct JavaScript and jQuery script references in place for client
side validation. See Model Validation for more information.
When a server side validation error occurs (for example when you have custom server side validation or client-side
validation is disabled), MVC places that error message as the body of the <span> element.
<span class="field-validation-error" data-valmsg-for="Email"
data-valmsg-replace="true">
The Email Address field is required.
</span>

The Validation Summary Tag Helper


• Targets <div> elements with the asp-validation-summary attribute
• HTML Helper alternative: @Html.ValidationSummary
The Validation Summary Tag Helper is used to display a summary of validation messages. The
asp-validation-summary attribute value can be any of the following:
asp-validation-summary Validation messages displayed
ValidationSummary.All Property and model level
ValidationSummary.ModelOnly Model
ValidationSummary.None None

Sample In the following example, the data model is decorated with DataAnnotation attributes, which generates
validation error messages on the <input> element. When a validation error occurs, the Validation Tag Helper
displays the error message:
using System.ComponentModel.DataAnnotations;

namespace FormsTagHelper.ViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}

@model RegisterViewModel

<form asp-controller="Demo" asp-action="RegisterValidation" method="post">


<div asp-validation-summary="ValidationSummary.ModelOnly"></div>
Email: <input asp-for="Email" /> <br />
<span asp-validation-for="Email"></span><br />
Password: <input asp-for="Password" /><br />
<span asp-validation-for="Password"></span><br />

1.5. MVC 245


ASP.NET 5 Documentation, Release

<button type="submit">Register</button>
</form>

The generated HTML (when the model is valid):


<form action="/DemoReg/Register" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul></div>
Email: <input name="Email" id="Email" type="email" value=""
data-val-required="The Email field is required."
data-val-email="The Email field is not a valid e-mail address."
data-val="true"> <br>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="Email"></span><br>
Password: <input name="Password" id="Password" type="password"
data-val-required="The Password field is required." data-val="true"><br>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="Password"></span><br>
<button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The Select Tag Helper

• Generates select and associated option elements for properties of your model.
• Has an HTML Helper alternative Html.DropDownListFor and Html.ListBoxFor
The Select Tag Helper asp-for specifies the model property name for the select element and asp-items specifies
the option elements. For example:
<select asp-for="Country" asp-items="Model.Countries"></select>

Sample:
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;

public class CountryViewModel


{
public string Country { get; set; }

public List<SelectListItem> Countries { get; } = new List<SelectListItem>


{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
};
}

The Index method initializes the CountryViewModel, sets the selected country and passes it to the Index view.
public IActionResult Index()
{
var model = new CountryViewModel();
model.Country = "CA";
return View(model);
}

246 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The HTTP POST Index method displays the selection:


[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(CountryViewModel model)
{
if (ModelState.IsValid)
{
var msg = model.Country + " selected";
return RedirectToAction("IndexSuccess", new { message = msg});
}

// If we got this far, something failed; redisplay form.


return View(model);
}

The Index view:


@model CountryViewModel

<form asp-controller="Home" asp-action="Index" method="post">


<select asp-for="Country" asp-items="Model.Countries"></select>
<br /><button type="submit">Register</button>
</form>

Which generates the following HTML (with “CA” selected):


<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option selected="selected" value="CA">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Note We do not recommend using ViewBag or ViewData with the Select Tag Helper. A view model
is more robust at providing MVC metadata and generally less problematic.
The asp-for attribute value is a special case and doesn’t require a Model prefix, the other Tag Helper attributes do
(such as asp-items)
<select asp-for="Country" asp-items="Model.Countries"></select>

Enum binding It’s often convenient to use <select> with an enum property and generate the SelectListItem
elements from the enum values.
Sample:
public class CountryEnumViewModel
{
public CountryEnum EnumCountry { get; set; }
}

using System.ComponentModel.DataAnnotations;

public enum CountryEnum


{

1.5. MVC 247


ASP.NET 5 Documentation, Release

Mexico,
USA,
Canada,
France,
Germany,
Spain
}

The GetEnumSelectList method generates a SelectList object for an enum.


@model CountryEnumViewModel

<form asp-controller="Home" asp-action="IndexEnum" method="post">


<select asp-for="EnumCountry"
asp-items="Html.GetEnumSelectList<CountryEnum>()"> >
</select>
<br /><button type="submit">Register</button>
</form>

You can decorate your enumerator list with the Display attribute to get a richer UI:
using System.ComponentModel.DataAnnotations;

public enum CountryEnum


{
[Display(Name = "United Mexican States")]
Mexico,
[Display(Name = "United States of America")]
USA,
Canada,
France,
Germany,
Spain
}

The following HTML is generated:


<form method="post" action="/Home/IndexEnum">
<select data-val="true" data-val-required="The EnumCountry field is required."
id="EnumCountry" name="EnumCountry">
<option value="0">United Mexican States</option>
<option value="1">United States of America</option>
<option value="2">Canada</option>
<option value="3">France</option>
<option value="4">Germany</option>
<option selected="selected" value="5">Spain</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Option Group The HTML <optgroup> element is generated when the view model contains one or more SelectList-
Group objects.
The CountryViewModelGroup groups the SelectListItem elements into the “North America” and “Europe”
groups:

248 Chapter 1. Topics


ASP.NET 5 Documentation, Release

public class CountryViewModelGroup


{
public CountryViewModelGroup()
{
var NorthAmericaGroup = new SelectListGroup { Name = "North America" };
var EuropeGroup = new SelectListGroup { Name = "Europe" };

Countries = new List<SelectListItem>


{
new SelectListItem
{
Value = "MEX",
Text = "Mexico",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "CAN",
Text = "Canada",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "US",
Text = "USA",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "FR",
Text = "France",
Group = EuropeGroup
},
new SelectListItem
{
Value = "ES",
Text = "Spain",
Group = EuropeGroup
},
new SelectListItem
{
Value = "DE",
Text = "Germany",
Group = EuropeGroup
}
};
}

public string Country { get; set; }

public List<SelectListItem> Countries { get; }


}

The two groups are shown below:

1.5. MVC 249


ASP.NET 5 Documentation, Release

The generated HTML:


<form method="post" action="/Home/IndexGroup">
<select id="Country" name="Country">
<optgroup label="North America">
<option value="MEX">Mexico</option>
<option value="CAN">Canada</option>
<option value="US">USA</option>
</optgroup>
<optgroup label="Europe">
<option value="FR">France</option>
<option value="ES">Spain</option>
<option value="DE">Germany</option>
</optgroup>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Multiple select The Select Tag Helper will automatically generate the multiple = “multiple” attribute if the property
specified in the asp-for attribute is an IEnumerable. For example, given the following model:
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;

public class CountryViewModelIEnumerable


{
public IEnumerable<string> CountryCodes { get; set; }

public List<SelectListItem> Countries { get; } = new List<SelectListItem>


{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },

250 Chapter 1. Topics


ASP.NET 5 Documentation, Release

new SelectListItem { Value = "FR", Text = "France" },


new SelectListItem { Value = "ES", Text = "Spain" },
new SelectListItem { Value = "DE", Text = "Germany"}
};
}

With the following view:


@model CountryViewModelIEnumerable

<form asp-controller="Home" asp-action="IndexMultiSelect" method="post">


<select asp-for="CountryCodes" asp-items="Model.Countries"></select>
<br /><button type="submit">Register</button>
</form>

Generates the following HTML:


<form method="post" action="/Home/IndexMultiSelect">
<select id="CountryCodes"
multiple="multiple"
name="CountryCodes"><option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
<option value="FR">France</option>
<option value="ES">Spain</option>
<option value="DE">Germany</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

No selection To allow for no selection, add a “not specified” option to the select list. If the property is a value type,
you’ll have to make it nullable.
@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


<select asp-for="Country" asp-items="Model.Countries">
<option value="">&lt;none&gt;</option>
</select>
<br /><button type="submit">Register</button>
</form>

If you find yourself using the “not specified” option in multiple pages, you can create a template to eliminate repeating
the HTML:
@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


@Html.EditorForModel()
<br /><button type="submit">Register</button>
</form>

The Views/Shared/EditorTemplates/CountryViewModel.cshtml template:


@model CountryViewModel

<select asp-for="Country" asp-items="Model.Countries">

1.5. MVC 251


ASP.NET 5 Documentation, Release

<option value="">--none--</option>
</select>

Adding HTML <option> elements is not limited to the No selection case. For example, the following view and action
method will generate HTML similar to the code above:
public IActionResult IndexOption(int id)
{
var model = new CountryViewModel();
model.Country = "CA";
return View(model);
}

@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


<select asp-for="Country">
<option value="">&lt;none&gt;</option>
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
</form>

The correct <option> element will be selected ( contain the selected="selected" attribute) depending on
the current Country value.
<form method="post" action="/Home/IndexEmpty">
<select id="Country" name="Country">
<option value="">&lt;none&gt;</option>
<option value="MX">Mexico</option>
<option value="CA" selected="selected">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Additional Resources

• Tag Helpers
• HTML Form element
• Request Verification Token
• Model Binding
• Model Validation
• data annotations
• Code snippets for this document.

HTML Helpers

Note: We are currently working on this topic.

252 Chapter 1. Topics


ASP.NET 5 Documentation, Release

We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Tag Helpers

Introduction to Tag Helpers

By Rick Anderson
• What are Tag Helpers?
• What Tag Helpers provide
• Managing Tag Helper scope
• IntelliSense support for Tag Helpers
• Tag Helpers compared to HTML Helpers
• Tag Helpers compared to Web Server Controls
• Customizing the Tag Helper element font
• Additional Resources

What are Tag Helpers? Tag Helpers enable server-side code to participate in creating and rendering HTML ele-
ments in Razor files. For example, the built-in ImageTagHelper can append a version number to the image name.
Whenever the image changes, the server generates a new unique version for the image, so clients are guaranteed to
get the current image (instead of a stale cached image). There are many built-in Tag Helpers for common tasks -
such as creating forms, links, loading assets and more - and even more available in public GitHub repositories and as
NuGet packages. Tag Helpers are authored in C#, and they target HTML elements based on element name, attribute
name, or parent tag. For example, the built-in LabelTagHelper can target the HTML <label> element when the
LabelTagHelper attributes are applied. If you’re familiar with HTML Helpers, Tag Helpers reduce the explicit
transitions between HTML and C# in Razor views. Tag Helpers compared to HTML Helpers explains the differences
in more detail.

What Tag Helpers provide


An HTML-friendly development experience For the most part, Razor markup using Tag Helpers looks like standard
HTML. Front-end designers conversant with HTML/CSS/JavaScript can edit Razor without learning C# Razor
syntax.
A rich IntelliSense environment for creating HTML and Razor markup This is in sharp contrast to HTML
Helpers, the previous approach to server-side creation of markup in Razor views. Tag Helpers compared to
HTML Helpers explains the differences in more detail. IntelliSense support for Tag Helpers explains the Intel-
liSense environment. Even developers experienced with Razor C# syntax are more productive using Tag Helpers
than writing C# Razor markup.
A way to make you more productive and able to produce more robust, reliable, and maintainable code using information only av
For example, historically the mantra on updating images was to change the name of the image when you change
the image. Images should be aggressively cached for performance reasons, and unless you change the name
of an image, you risk clients getting a stale copy. Historically, after an image was edited, the name had to be

1.5. MVC 253


ASP.NET 5 Documentation, Release

changed and each reference to the image in the web app needed to be updated. Not only is this very labor
intensive, it’s also error prone (you could miss a reference, accidentally enter the wrong string, etc.) The built-in
ImageTagHelper can do this for you automatically. The ImageTagHelper can append a version number to
the image name, so whenever the image changes, the server automatically generates a new unique version for
the image. Clients are guaranteed to get the current image. This robustness and labor savings comes essentially
free by using the ImageTagHelper.
Most of the built-in Tag Helpers target existing HTML elements and provide server-side attributes for the element.
For example, the <input> element used in many of the views in the Views/Account folder contains the asp-for
attribute, which extracts the name of the specified model property into the rendered HTML. The following Razor
markup:
<label asp-for="Email"></label>

Generates the following HTML:


<label for="Email">Email</label>

The asp-for attribute is made available by the For property in the LabelTagHelper. See Authoring Tag Helpers
for more information.

Managing Tag Helper scope Tag Helpers scope is controlled by a combination of @addTagHelper,
@removeTagHelper, and the ”!” opt-out character.

@addTagHelper makes Tag Helpers available If you create a new ASP.NET Core web app named Authoring-
TagHelpers (with no authentication), the following Views/_ViewImports.cshtml file will be added to your project:
@using AuthoringTagHelpers
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"

The @addTagHelper directive makes Tag Helpers available to the view. In this case, the view file is
Views/_ViewImports.cshtml, which by default is inherited by all view files in the Views folder and sub-directories;
making Tag Helpers available. The code above uses the wildcard syntax (“*”) to specify that all Tag Helpers in the
specified assembly (Microsoft.AspNet.Mvc.TagHelpers) will be available to every view file in the Views directory or
sub-directory. The first parameter after @addTagHelper specifies the Tag Helpers to load (we are using “*” for all
Tag Helpers), and the second parameter “Microsoft.AspNet.Mvc.TagHelpers” specifies the assembly containing the
Tag Helpers. Microsoft.AspNet.Mvc.TagHelpers is the assembly for the built-in ASP.NET Core Tag Helpers.
To expose all of the Tag Helpers in this project (which creates an assembly named AuthoringTagHelpers), you would
use the following:
@using AuthoringTagHelpers
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "*, AuthoringTagHelpers"

If your project contains an EmailTagHelper with the default namespace


(AuthoringTagHelpers.TagHelpers.EmailTagHelper), you can provide the fully qualified name
(FQN) of the Tag Helper:
@using AuthoringTagHelpers
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers"

To add a Tag Helper to a view using an FQN, you first add the FQN
(AuthoringTagHelpers.TagHelpers.EmailTagHelper), and then the assembly name (Authoring-
TagHelpers). Most developers prefer to use the “*” wildcard syntax. The wildcard syntax allows you to insert

254 Chapter 1. Topics


ASP.NET 5 Documentation, Release

the wildcard character “*” as the suffix in an FQN. For example, any of the following directives will bring in the
EmailTagHelper:
@addTagHelper "AuthoringTagHelpers.TagHelpers.E*, AuthoringTagHelpers"
@addTagHelper "AuthoringTagHelpers.TagHelpers.Email*, AuthoringTagHelpers"

As mentioned previously, adding the @addTagHelper directive to the Views/_ViewImports.cshtml file makes the
Tag Helper available to all view files in the Views directory and sub-directories. You can use the @addTagHelper
directive in specific view files if you want to opt-in to exposing the Tag Helper to only those views.

@removeTagHelper removes Tag Helpers The @removeTagHelper has the same two parameters as
@addTagHelper, and it removes a Tag Helper that was previously added. For example, @removeTagHelper
applied to a specific view removes the specified Tag Helper from the view. Using @removeTagHelper in a
Views/Folder/_ViewImports.cshtml file removes the specified Tag Helper from all of the views in Folder.

Controlling Tag Helper scope with the _ViewImports.cshtml file You can add a _ViewImports.cshtml to any
view folder, and the view engine adds the directives from that _ViewImports.cshtml file to those contained in the
Views/_ViewImports.cshtml file. If you added an empty Views/Home/_ViewImports.cshtml file for the Home views,
there would be no change because the _ViewImports.cshtml file is additive. Any @addTagHelper directives you
add to the Views/Home/_ViewImports.cshtml file (that are not in the default Views/_ViewImports.cshtml file) would
expose those Tag Helpers to views only in the Home folder.

Opting out of individual elements You can disable a Tag Helper at the element level with the Tag Helper opt-out
character (”!”). For example, Email validation is disabled in the <span> with the Tag Helper opt-out character:
<!span asp-validation-for="Email" class="text-danger"></!span>

You must apply the Tag Helper opt-out character to the opening and closing tag. (The Visual Studio editor automat-
ically adds the opt-out character to the closing tag when you add one to the opening tag). After you add the opt-out
character, the element and Tag Helper attributes are no longer displayed in a distinctive font.

Using @tagHelperPrefix to make Tag Helper usage explicit The @tagHelperPrefix directive allows
you to specify a tag prefix string to enable Tag Helper support and to make Tag Helper usage explicit. In the code
image below, the Tag Helper prefix is set to th:, so only those elements using the prefix th: support Tag Helpers
(Tag Helper-enabled elements have a distinctive font). The <label> and <input> elements have the Tag Helper
prefix and are Tag Helper-enabled, while the <span> element does not.

The same hierarchy rules that apply to @addTagHelper also apply to @tagHelperPrefix.

IntelliSense support for Tag Helpers When you create a new ASP.NET web app in Visual Studio, it adds “Mi-
crosoft.AspNet.Tooling.Razor” to the project.json file. This is the package that adds Tag Helper tooling.
Consider writing an HTML <label> element. As soon as you enter <l in the Visual Studio editor, IntelliSense
displays matching elements:

1.5. MVC 255


ASP.NET 5 Documentation, Release

Not only do you get HTML help, but the icon (the “@” symbol with “<>” under it).

identifies the element as targeted by Tag Helpers. Pure HTML elements (such as the fieldset) display the “<>”icon.
A pure HTML <label> tag displays the HTML tag (with the default Visual Studio color theme) in a brown font, the
attributes in red, and the attribute values in blue.

After you enter <label, IntelliSense lists the available HTML/CSS attributes and the Tag Helper-targeted attributes:

IntelliSense statement completion allows you to enter the tab key to complete the statement with the selected value:

As soon as a Tag Helper attribute is entered, the tag and attribute fonts change. Using the default Visual Studio “Blue”
or “Light” color theme, the font is bold purple. If you’re using the “Dark” theme the font is bold teal. The images in
this document were taken using the default theme.

256 Chapter 1. Topics


ASP.NET 5 Documentation, Release

You can enter the Visual Studio CompleteWord shortcut (Ctrl +spacebar is the default) inside the double quotes (“”),
and you are now in C#, just like you would be in a C# class. IntelliSense displays all the methods and properties on
the page model. The methods and properties are available because the property type is ModelExpression. In the
image below, I’m editing the Register view, so the RegisterViewModel is available.

IntelliSense lists the properties and methods available to the model on the page. The rich IntelliSense environment
helps you select the CSS class:

Tag Helpers compared to HTML Helpers Tag Helpers attach to HTML elements in Razor views, while HTML
Helpers are invoked as methods interspersed with HTML in Razor views. Consider the following Razor markup,
which creates an HTML label with the CSS class “caption”:
@Html.Label("FirstName", "First Name:", new {@class="caption"})

The at (@) symbol tells Razor this is the start of code. The next two parameters (“FirstName” and “First Name:”) are
strings, so IntelliSense can’t help. The last argument:
new {@class="caption"}

1.5. MVC 257


ASP.NET 5 Documentation, Release

Is an anonymous object used to represent attributes. Because class is a reserved keyword in C#, you use the @ symbol
to force C# to interpret “@class=” as a symbol (property name). To a front-end designer (someone familiar with
HTML/CSS/JavaScript and other client technologies but not familiar with C# and Razor), most of the line is foreign.
The entire line must be authored with no help from IntelliSense.
Using the LabelTagHelper, the same markup can be written as:

With the Tag Helper version, as soon as you enter <l in the Visual Studio editor, IntelliSense displays matching
elements:

IntelliSense helps you write the entire line. The LabelTagHelper also defaults to setting the content of the
asp-for attribute value (“FirstName”) to “First Name”; It converts camel-cased properties to a sentence composed
of the property name with a space where each new upper-case letter occurs. In the following markup:

generates:
<label class="caption" for="FirstName">First Name</label>

The camel-cased to sentence-cased content is not used if you add content to the <label>. For example:

generates:
<label class="caption" for="FirstName">Name First</label>

The following code image shows the Form portion of the Views/Account/Register.cshtml Razor view generated from
the legacy ASP.NET 4.5.x MVC template included with Visual Studio 2015.

258 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The Visual Studio editor displays C# code with a grey background. For example, the AntiForgeryToken HTML
Helper:
@Html.AntiForgeryToken()

is displayed with a grey background. Most of the markup in the Register view is C#. Compare that to the equivalent
approach using Tag Helpers:

1.5. MVC 259


ASP.NET 5 Documentation, Release

The markup is much cleaner and easier to read, edit, and maintain than the HTML Helpers approach. The C# code is
reduced to the minimum that the server needs to know about. The Visual Studio editor displays markup targeted by a
Tag Helper in a distinctive font.
Consider the Email group:
<div class="form-group">
<label asp-for="Email" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>

Each of the “asp-” attributes has a value of “Email”, but “Email” is not a string. In this context, “Email” is the C#
model expression property for the RegisterViewModel.
The Visual Studio editor helps you write all of the markup in the Tag Helper approach of the register form, while
Visual Studio provides no help for most of the code in the HTML Helpers approach. IntelliSense support for Tag
Helpers goes into detail on working with Tag Helpers in the Visual Studio editor.

Tag Helpers compared to Web Server Controls

260 Chapter 1. Topics


ASP.NET 5 Documentation, Release

• Tag Helpers don’t own the element they’re associated with; they simply participate in the rendering of the
element and content. ASP.NET Web Server controls are declared and invoked on a page.
• Web Server controls have a non-trivial lifecycle that can make developing and debugging difficult.
• Web Server controls allow you to add functionality to the client Document Object Model (DOM) elements by
using a client control. Tag Helpers have no DOM.
• Web Server controls include automatic browser detection. Tag Helpers have no knowledge of the browser.
• Multiple Tag Helpers can act on the same element (see Avoiding Tag Helper conflicts ) while you typically can’t
compose Web Server controls.
• Tag Helpers can modify the tag and content of HTML elements that they’re scoped to, but don’t directly modify
anything else on a page. Web Server controls have a less specific scope and can perform actions that affect other
parts of your page; enabling unintended side effects.
• Web Server controls use type converters to convert strings into objects. With Tag Helpers, you work natively in
C#, so you don’t need to do type conversion.
• Web Server controls use System.ComponentModel to implement the run-time and design-time behavior of com-
ponents and controls. System.ComponentModel includes the base classes and interfaces for implement-
ing attributes and type converters, binding to data sources, and licensing components. Contrast that to Tag
Helpers, which typically derive from TagHelper, and the TagHelper base class exposes only two methods,
Process and ProcessAsync.

Customizing the Tag Helper element font You can customize the font and colorization from Tools > Options >
Environment > Fonts and Colors:

1.5. MVC 261


ASP.NET 5 Documentation, Release

Additional Resources
• Authoring Tag Helpers
• Working with Forms (Tag Helpers)
• TagHelperSamples on GitHub contains Tag Helper samples for working with Bootstrap.

Working with Forms

By Rick Anderson, Dave Paquette and Jerrie Pelser


This document demonstrates working with Forms and the HTML elements commonly used on a Form. The HTML
Form element provides the primary mechanism web apps use to post back data to the server. Most of this document
describes Tag Helpers and how they can help you productively create robust HTML forms. We recommend you read
Introduction to Tag Helpers before you read this document.
In many cases, HTML Helpers provide an alternative approach to a specific Tag Helper, but it’s important to recognize
that Tag Helpers do not replace HTML Helpers and there is not a Tag Helper for each HTML Helper. When an HTML
Helper alternative exists, it is mentioned.

262 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Sections:
• The Form Tag Helper
• The Input Tag Helper
• The Textarea Tag Helper
• The Label Tag Helper
• The Validation Tag Helpers
• The Select Tag Helper
• Additional Resources

The Form Tag Helper The Form Tag Helper:


• Generates the HTML <FORM> action attribute value for a MVC controller action or named route
• Generates a hidden Request Verification Token to prevent cross-site request forgery (when used with the
[ValidateAntiForgeryToken] attribute in the HTTP Post action method)
• Provides the asp-route-<Parameter Name> attribute, where <Parameter Name> is added to the
route values. The routeValues parameters to Html.BeginForm and Html.BeginRouteForm provide
similar functionality.
• Has an HTML Helper alternative Html.BeginForm and Html.BeginRouteForm
Sample:
<form asp-controller="Demo" asp-action="Register" method="post">
<!-- Input and Submit elements -->
</form>

The Form Tag Helper above generates the following HTML:


<form method="post" action="/Demo/Register">
<!-- Input and Submit elements -->
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The MVC runtime generates the action attribute value from the Form Tag Helper attributes asp-controller
and asp-action. The Form Tag Helper also generates a hidden Request Verification Token to prevent cross-site
request forgery (when used with the [ValidateAntiForgeryToken] attribute in the HTTP Post action method).
Protecting a pure HTML Form from cross-site request forgery is very difficult, the Form Tag Helper provides this
service for you.

Using a named route The asp-route Tag Helper attribute can also generate markup for the HTML action
attribute. An app with a route named register could use the following markup for the registration page:
<form asp-route="register" method="post">
<!-- Input and Submit elements -->
</form>

Many of the views in the Views/Account folder (generated when you create a new web app with Individual User
Accounts) contain the asp-route-returnurl attribute:
<form asp-controller="Account" asp-action="Login"
asp-route-returnurl="@ViewData["ReturnUrl"]"
method="post" class="form-horizontal" role="form">

1.5. MVC 263


ASP.NET 5 Documentation, Release

Note With the built in templates, returnUrl is only populated automatically when you try to access
an authorized resource but are not authenticated or authorized. When you attempt an unauthorized
access, the security middleware redirects you to the login page with the returnUrl set.

The Input Tag Helper The Input Tag Helper binds an HTML <input> element to a model expression in your razor
view.
Syntax:
<input asp-for="<Expression Name>" />

The Input Tag Helper:


• Generates the id and name HTML attributes for the expression name specified in the asp-for attribute.
asp-for="Property1.Property2" is equivalent to m => m.Property1.Property2, that is the
attribute value literally is part of an expression. The name of the expression is what’s used for the asp-for
attribute value.
• Sets the HTML type attribute value based on the model type and data annotation attributes applied to the model
property
• Will not overwrite the HTML type attribute value when one is specified
• Generates HTML5 validation attributes from data annotation attributes applied to model properties
• Has an HTML Helper feature overlap with Html.TextBoxFor and Html.EditorFor. See the HTML
Helper alternatives to Input Tag Helper section for details.
• Provides strong typing. If the name of the property changes and you don’t update the Tag Helper you’ll get an
error similar to the following:
An error occurred during the compilation of a resource required to process
this request. Please review the following specific error details and modify
your source code appropriately.

Type expected
'RegisterViewModel' does not contain a definition for 'Email' and no
extension method 'Email' accepting a first argument of type 'RegisterViewModel'
could be found (are you missing a using directive or an assembly reference?)

The Input Tag Helper sets the HTML type attribute based on the .NET type. The following table lists some
common .NET types and generated HTML type (not every .NET type is listed).
.NET type Input Type
Bool type=”checkbox”
String type=”text”
DateTime type=”datetime”
Byte type=”number”
Int type=”number”
Single, Double type=”number”
The following table shows some common data annotations attributes that the input tag helper will map to specific input
types (not every validation attribute is listed):

264 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Attribute Input Type


[EmailAddress] type=”email”
[Url] type=”url”
[HiddenInput] type=”hidden”
[Phone] type=”tel”
[DataType(DataType.Password)] type=”password”
[DataType(DataType.Date)] type=”date”
[DataType(DataType.Time)] type=”time”
Sample:
using System.ComponentModel.DataAnnotations;

namespace FormsTagHelper.ViewModels
{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}

@model RegisterViewModel

<form asp-controller="Demo" asp-action="RegisterInput" method="post">


Email: <input asp-for="Email" /> <br />
Password: <input asp-for="Password" /><br />
<button type="submit">Register</button>
</form>

The code above generates the following HTML:


<form method="post" action="/Demo/RegisterInput">
Email:
<input type="email" data-val="true"
data-val-email="The Email Address field is not a valid e-mail address."
data-val-required="The Email Address field is required."
id="Email" name="Email" value="" /> <br>
Password:
<input type="password" data-val="true"
data-val-required="The Password field is required."
id="Password" name="Password" /><br>
<button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The data annotations applied to the Email and Password properties generate metadata on the model. The Input Tag
Helper consumes the model metadata and produces HTML5 data-val-* attributes (see Model Validation). These
attributes describe the validators to attach to the input fields. This provides unobtrusive HTML5 and jQuery validation.
The unobtrusive attributes have the format data-val-rule="Error Message", where rule is the name of
the validation rule (such as data-val-required, data-val-email, data-val-maxlength, etc.) If an
error message is provided in the attribute, it is displayed as the value for the data-val-rule attribute. There are
also attributes of the form data-val-ruleName-argumentName="argumentValue" that provide additional

1.5. MVC 265


ASP.NET 5 Documentation, Release

details about the rule, for example, data-val-maxlength-max="1024" .

HTML Helper alternatives to Input Tag Helper Html.TextBox, Html.TextBoxFor, Html.Editor


and Html.EditorFor have overlapping features with the Input Tag Helper. The Input Tag Helper will au-
tomatically set the type attribute; Html.TextBox and Html.TextBoxFor will not. Html.Editor and
Html.EditorFor handle collections, complex objects and templates; the Input Tag Helper does not. The In-
put Tag Helper, Html.EditorFor and Html.TextBoxFor are strongly typed (they use lambda expressions);
Html.TextBox and Html.Editor are not (they use expression names).

Expression names The asp-for attribute value is a ModelExpression and the right hand side of a lambda expres-
sion. Therefore, asp-for="Property1" becomes m => m.Property1 in the generated code which is why
you don’t need to prefix with Model. You can use the “@” character to start an inline expression and move before the
m.:
@{
var joe = "Joe";
}
<input asp-for="@joe" />

Generates the following:


<input type="text" id="joe" name="joe" value="Joe" />

Navigating child properties You can also navigate to child properties using the property path of the view model.
Consider a more complex model class that contains a child Address property.
public class AddressViewModel
{
public string AddressLine1 { get; set; }
}

public class RegisterAddressViewModel


{
public string Email { get; set; }

[DataType(DataType.Password)]
public string Password { get; set; }

public AddressViewModel Address { get; set; }


}

In the view, we bind to Address.AddressLine1:


@model RegisterAddressViewModel

<form asp-controller="Demo" asp-action="RegisterAddress" method="post">


Email: <input asp-for="Email" /> <br />
Password: <input asp-for="Password" /><br />
Address: <input asp-for="Address.AddressLine1" /><br />
<button type="submit">Register</button>
</form>

The following HTML is generated for Address.AddressLine1:


<input type="text" id="Address_AddressLine1" name="Address.AddressLine1" value="" />

266 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Expression names and Collections Sample, a model containing an array of Colors:


public class Person
{
public List<string> Colors { get; set; }

public int Age { get; set; }


}

The action method:


public IActionResult Edit(int id, int colorIndex)
{
ViewData["Index"] = colorIndex;
return View(GetPerson(id));
}

The following Razor shows how you access a specific Color element:
@model Person
@{
var index = (int)ViewData["index"];
}

<form asp-controller="ToDo" asp-action="Edit" method="post">


@Html.EditorFor(m => m.Colors[index])
<label asp-for="Age"></label>
<input asp-for="Age" /><br />
<button type="submit">Post</button>
</form>

The Views/Shared/EditorTemplates/String.cshtml template:


@model string

<label asp-for="@Model"></label>
<input asp-for="@Model" /> <br />

Sample using List<T>:


public class ToDoItem
{
public string Name { get; set; }

public bool IsDone { get; set; }

The following Razor shows how to iterate over a collection:


@model List<ToDoItem>

<form asp-controller="ToDo" asp-action="Edit" method="post">


<table>
<tr> <th>Name</th> <th>Is Done</th> </tr>

@for (int i = 0; i < Model.Count; i++)


{
<tr>
@Html.EditorFor(model => model[i])
</tr>
}

1.5. MVC 267


ASP.NET 5 Documentation, Release

</table>
<button type="submit">Save</button>
</form>

The Views/Shared/EditorTemplates/ToDoItem.cshtml template:


@model ToDoItem

<td>
<label asp-for="@Model.Name"></label>
@Html.DisplayFor(model => model.Name)
</td>
<td>
<input asp-for="@Model.IsDone" />
</td>

@*
This template replaces the following Razor which evaluates the indexer three times.
<td>
<label asp-for="@Model[i].Name"></label>
@Html.DisplayFor(model => model[i].Name)
</td>
<td>
<input asp-for="@Model[i].IsDone" />
</td>
*@

Note Always use for (and not foreach) to iterate over a list. Evaluating an indexer in a LINQ expres-
sion can be expensive and should be minimized.
Note The commented sample code above shows how you would replace the lambda expression with the
@ operator to access each ToDoItem in the list.

The Textarea Tag Helper The Textarea Tag Helper tag helper is similar to the Input Tag Helper.
• Generates the id and name attributes, and the data validation attributes from the model for a <textarea> element.
• Provides strong typing.
• HTML Helper alternative: Html.TextAreaFor
Sample:
using System.ComponentModel.DataAnnotations;

public class DescriptionViewModel


{
[MinLength(5)]
[MaxLength(1024)]
public string Description { get; set; }
}

@model DescriptionViewModel

<form asp-controller="Demo" asp-action="RegisterTextArea" method="post">


<textarea asp-for="Description"></textarea>
<button type="submit">Test</button>
</form>

268 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The following HTML is generated:


<form method="post" action="/Demo/RegisterTextArea">
<textarea data-val="true"
data-val-maxlength="The field Description must be a string or array type with a maximum length of
data-val-maxlength-max="1024"
data-val-minlength="The field Description must be a string or array type with a minimum length of
data-val-minlength-min="5"
id="Description" name="Description">
</textarea>
<button type="submit">Test</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The Label Tag Helper


• Generates the label caption and for attribute on a <label> element for an expression name
• HTML Helper alternative: Html.LabelFor.
The Label Tag Helper provides the following benefits over a pure HTML label element:
• You automatically get the descriptive label value from the Display attribute. The intended display name might
change over time, and the combination of Display attribute and Label Tag Helper will apply the Display
everywhere it’s used.
• Less markup in source code
• Strong typing with the model property.
Sample:
using System.ComponentModel.DataAnnotations;
public class SimpleViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }
}

@model SimpleViewModel

<form asp-controller="Demo" asp-action="RegisterLabel" method="post">


<label asp-for="Email"></label>
<input asp-for="Email" /> <br />
</form>

The following HTML is generated for the <label> element:


<label for="Email">Email Address</label>

The Label Tag Helper generated the for attribute value of “Email”, which is the ID associated with the <input>
element. The Tag Helpers generate consistent id and for elements so they can be correctly associated. The caption
in this sample comes from the Display attribute. If the model didn’t contain a Display attribute, the caption would
be the property name of the expression.

The Validation Tag Helpers There are two Validation Tag Helpers. The Validation Message Tag Helper (which
displays a validation message for a single property on your model), and the Validation Summary Tag Helper (which
displays a summary of validation errors). The Input Tag Helper adds HTML5 client side validation attributes to input

1.5. MVC 269


ASP.NET 5 Documentation, Release

elements based on data annotation attributes on your model classes. Validation is also performed on the server. The
Validation Tag Helper displays these error messages when a validation error occurs.

The Validation Message Tag Helper


• Adds the HTML5 data-valmsg-for="property" attribute to the span element, which attaches the val-
idation error messages on the input field of the specified model property. When a client side validation error
occurs, jQuery displays the error message in the <span> element.
• Validation also takes place on the server. Clients may have JavaScript disabled and some validation can only be
done on the server side.
• HTML Helper alternative: Html.ValidationMessageFor
The Validation Message Tag Helper is used with the asp-validation-for attribute on a HTML span element.
<span asp-validation-for="Email">

The Validation Message Tag Helper will generate the following HTML:
<span class="field-validation-valid"
data-valmsg-for="Email"
data-valmsg-replace="true">

You generally use the Validation Message Tag Helper after an Input Tag Helper for the same property. Doing so
displays any validation error messages near the input that caused the error.
Note You must have a view with the correct JavaScript and jQuery script references in place for client
side validation. See Model Validation for more information.
When a server side validation error occurs (for example when you have custom server side validation or client-side
validation is disabled), MVC places that error message as the body of the <span> element.
<span class="field-validation-error" data-valmsg-for="Email"
data-valmsg-replace="true">
The Email Address field is required.
</span>

The Validation Summary Tag Helper


• Targets <div> elements with the asp-validation-summary attribute
• HTML Helper alternative: @Html.ValidationSummary
The Validation Summary Tag Helper is used to display a summary of validation messages. The
asp-validation-summary attribute value can be any of the following:
asp-validation-summary Validation messages displayed
ValidationSummary.All Property and model level
ValidationSummary.ModelOnly Model
ValidationSummary.None None

Sample In the following example, the data model is decorated with DataAnnotation attributes, which generates
validation error messages on the <input> element. When a validation error occurs, the Validation Tag Helper
displays the error message:
using System.ComponentModel.DataAnnotations;

namespace FormsTagHelper.ViewModels

270 Chapter 1. Topics


ASP.NET 5 Documentation, Release

{
public class RegisterViewModel
{
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string Email { get; set; }

[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
}
}

@model RegisterViewModel

<form asp-controller="Demo" asp-action="RegisterValidation" method="post">


<div asp-validation-summary="ValidationSummary.ModelOnly"></div>
Email: <input asp-for="Email" /> <br />
<span asp-validation-for="Email"></span><br />
Password: <input asp-for="Password" /><br />
<span asp-validation-for="Password"></span><br />
<button type="submit">Register</button>
</form>

The generated HTML (when the model is valid):


<form action="/DemoReg/Register" method="post">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul></div>
Email: <input name="Email" id="Email" type="email" value=""
data-val-required="The Email field is required."
data-val-email="The Email field is not a valid e-mail address."
data-val="true"> <br>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="Email"></span><br>
Password: <input name="Password" id="Password" type="password"
data-val-required="The Password field is required." data-val="true"><br>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="Password"></span><br>
<button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

The Select Tag Helper


• Generates select and associated option elements for properties of your model.
• Has an HTML Helper alternative Html.DropDownListFor and Html.ListBoxFor
The Select Tag Helper asp-for specifies the model property name for the select element and asp-items specifies
the option elements. For example:
<select asp-for="Country" asp-items="Model.Countries"></select>

Sample:
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;

1.5. MVC 271


ASP.NET 5 Documentation, Release

public class CountryViewModel


{
public string Country { get; set; }

public List<SelectListItem> Countries { get; } = new List<SelectListItem>


{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
};
}

The Index method initializes the CountryViewModel, sets the selected country and passes it to the Index view.
public IActionResult Index()
{
var model = new CountryViewModel();
model.Country = "CA";
return View(model);
}

The HTTP POST Index method displays the selection:


[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Index(CountryViewModel model)
{
if (ModelState.IsValid)
{
var msg = model.Country + " selected";
return RedirectToAction("IndexSuccess", new { message = msg});
}

// If we got this far, something failed; redisplay form.


return View(model);
}

The Index view:


@model CountryViewModel

<form asp-controller="Home" asp-action="Index" method="post">


<select asp-for="Country" asp-items="Model.Countries"></select>
<br /><button type="submit">Register</button>
</form>

Which generates the following HTML (with “CA” selected):


<form method="post" action="/">
<select id="Country" name="Country">
<option value="MX">Mexico</option>
<option selected="selected" value="CA">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Note We do not recommend using ViewBag or ViewData with the Select Tag Helper. A view model

272 Chapter 1. Topics


ASP.NET 5 Documentation, Release

is more robust at providing MVC metadata and generally less problematic.


The asp-for attribute value is a special case and doesn’t require a Model prefix, the other Tag Helper attributes do
(such as asp-items)
<select asp-for="Country" asp-items="Model.Countries"></select>

Enum binding It’s often convenient to use <select> with an enum property and generate the SelectListItem
elements from the enum values.
Sample:
public class CountryEnumViewModel
{
public CountryEnum EnumCountry { get; set; }
}

using System.ComponentModel.DataAnnotations;

public enum CountryEnum


{
Mexico,
USA,
Canada,
France,
Germany,
Spain
}

The GetEnumSelectList method generates a SelectList object for an enum.


@model CountryEnumViewModel

<form asp-controller="Home" asp-action="IndexEnum" method="post">


<select asp-for="EnumCountry"
asp-items="Html.GetEnumSelectList<CountryEnum>()"> >
</select>
<br /><button type="submit">Register</button>
</form>

You can decorate your enumerator list with the Display attribute to get a richer UI:
using System.ComponentModel.DataAnnotations;

public enum CountryEnum


{
[Display(Name = "United Mexican States")]
Mexico,
[Display(Name = "United States of America")]
USA,
Canada,
France,
Germany,
Spain
}

The following HTML is generated:

1.5. MVC 273


ASP.NET 5 Documentation, Release

<form method="post" action="/Home/IndexEnum">


<select data-val="true" data-val-required="The EnumCountry field is required."
id="EnumCountry" name="EnumCountry">
<option value="0">United Mexican States</option>
<option value="1">United States of America</option>
<option value="2">Canada</option>
<option value="3">France</option>
<option value="4">Germany</option>
<option selected="selected" value="5">Spain</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Option Group The HTML <optgroup> element is generated when the view model contains one or more SelectList-
Group objects.
The CountryViewModelGroup groups the SelectListItem elements into the “North America” and “Europe”
groups:
public class CountryViewModelGroup
{
public CountryViewModelGroup()
{
var NorthAmericaGroup = new SelectListGroup { Name = "North America" };
var EuropeGroup = new SelectListGroup { Name = "Europe" };

Countries = new List<SelectListItem>


{
new SelectListItem
{
Value = "MEX",
Text = "Mexico",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "CAN",
Text = "Canada",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "US",
Text = "USA",
Group = NorthAmericaGroup
},
new SelectListItem
{
Value = "FR",
Text = "France",
Group = EuropeGroup
},
new SelectListItem
{
Value = "ES",
Text = "Spain",

274 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Group = EuropeGroup
},
new SelectListItem
{
Value = "DE",
Text = "Germany",
Group = EuropeGroup
}
};
}

public string Country { get; set; }

public List<SelectListItem> Countries { get; }


}

The two groups are shown below:

The generated HTML:


<form method="post" action="/Home/IndexGroup">
<select id="Country" name="Country">
<optgroup label="North America">
<option value="MEX">Mexico</option>
<option value="CAN">Canada</option>
<option value="US">USA</option>
</optgroup>
<optgroup label="Europe">
<option value="FR">France</option>
<option value="ES">Spain</option>
<option value="DE">Germany</option>
</optgroup>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />

1.5. MVC 275


ASP.NET 5 Documentation, Release

</form>

Multiple select The Select Tag Helper will automatically generate the multiple = “multiple” attribute if the property
specified in the asp-for attribute is an IEnumerable. For example, given the following model:
using Microsoft.AspNet.Mvc.Rendering;
using System.Collections.Generic;

public class CountryViewModelIEnumerable


{
public IEnumerable<string> CountryCodes { get; set; }

public List<SelectListItem> Countries { get; } = new List<SelectListItem>


{
new SelectListItem { Value = "MX", Text = "Mexico" },
new SelectListItem { Value = "CA", Text = "Canada" },
new SelectListItem { Value = "US", Text = "USA" },
new SelectListItem { Value = "FR", Text = "France" },
new SelectListItem { Value = "ES", Text = "Spain" },
new SelectListItem { Value = "DE", Text = "Germany"}
};
}

With the following view:


@model CountryViewModelIEnumerable

<form asp-controller="Home" asp-action="IndexMultiSelect" method="post">


<select asp-for="CountryCodes" asp-items="Model.Countries"></select>
<br /><button type="submit">Register</button>
</form>

Generates the following HTML:


<form method="post" action="/Home/IndexMultiSelect">
<select id="CountryCodes"
multiple="multiple"
name="CountryCodes"><option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
<option value="FR">France</option>
<option value="ES">Spain</option>
<option value="DE">Germany</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

No selection To allow for no selection, add a “not specified” option to the select list. If the property is a value type,
you’ll have to make it nullable.
@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


<select asp-for="Country" asp-items="Model.Countries">
<option value="">&lt;none&gt;</option>
</select>

276 Chapter 1. Topics


ASP.NET 5 Documentation, Release

<br /><button type="submit">Register</button>


</form>

If you find yourself using the “not specified” option in multiple pages, you can create a template to eliminate repeating
the HTML:
@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


@Html.EditorForModel()
<br /><button type="submit">Register</button>
</form>

The Views/Shared/EditorTemplates/CountryViewModel.cshtml template:


@model CountryViewModel

<select asp-for="Country" asp-items="Model.Countries">


<option value="">--none--</option>
</select>

Adding HTML <option> elements is not limited to the No selection case. For example, the following view and action
method will generate HTML similar to the code above:
public IActionResult IndexOption(int id)
{
var model = new CountryViewModel();
model.Country = "CA";
return View(model);
}

@model CountryViewModel

<form asp-controller="Home" asp-action="IndexEmpty" method="post">


<select asp-for="Country">
<option value="">&lt;none&gt;</option>
<option value="MX">Mexico</option>
<option value="CA">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
</form>

The correct <option> element will be selected ( contain the selected="selected" attribute) depending on
the current Country value.
<form method="post" action="/Home/IndexEmpty">
<select id="Country" name="Country">
<option value="">&lt;none&gt;</option>
<option value="MX">Mexico</option>
<option value="CA" selected="selected">Canada</option>
<option value="US">USA</option>
</select>
<br /><button type="submit">Register</button>
<input name="__RequestVerificationToken" type="hidden" value="<removed for brevity>" />
</form>

Additional Resources

1.5. MVC 277


ASP.NET 5 Documentation, Release

• Tag Helpers
• HTML Form element
• Request Verification Token
• Model Binding
• Model Validation
• data annotations
• Code snippets for this document.

Authoring Tag Helpers

By Rick Anderson

Sections:
• Getting started with Tag Helpers
• Starting the email Tag Helper
• A working email Tag Helper
• The bold Tag Helper
• Web site information Tag Helper
• Condition Tag Helper
• Inspecting and retrieving child content

View or download sample code

Getting started with Tag Helpers This tutorial provides an introduction to programming Tag Helpers. Introduction
to Tag Helpers describes the benefits that Tag Helpers provide.
A tag helper is any class that implements the ITagHelper interface. However, when you author a tag helper,
you generally derive from TagHelper, doing so gives you access to the Process method. We will introduce the
TagHelper methods and properties as we use them in this tutorial.
1. Create a new ASP.NET Core project called AuthoringTagHelpers. You won’t need authentication for this
project.
2. Create a folder to hold the Tag Helpers called TagHelpers. The TagHelpers folder is not required, but it is a
reasonable convention. Now let’s get started writing some simple tag helpers.

Starting the email Tag Helper In this section we will write a tag helper that updates an email tag. For example:
<email>Support</email>

The server will use our email tag helper to convert that markup into the following:
<a href="mailto:[email protected]">[email protected]</a>

That is, an anchor tag that makes this an email link. You might want to do this if you are writing a blog engine and
need it to send email for marketing, support, and other contacts, all to the same domain.
1. Add the following EmailTagHelper class to the TagHelpers folder.

278 Chapter 1. Topics


ASP.NET 5 Documentation, Release

using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using System.Threading.Tasks;

namespace AuthoringTagHelpers.TagHelpers
{
public class EmailTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a"; // Replaces <email> with <a> tag
}
}
}

Notes:
• Tag helpers use a naming convention that targets elements of the root class name (minus the TagHelper portion
of the class name). In this example, the root name of EmailTagHelper is email, so the <email> tag will be
targeted. This naming convention should work for most tag helpers, later on I’ll show how to override it.
• The EmailTagHelper class derives from TagHelper. The TagHelper class provides the rich methods
and properties we will examine in this tutorial.
• The overridden Process method controls what the tag helper does when executed. The TagHelper class
also provides an asynchronous version (ProcessAsync) with the same parameters.
• The context parameter to Process (and ProcessAsync) contains information associated with the execution
of the current HTML tag.
• The output parameter to Process (and ProcessAsync) contains a stateful HTML element representative of
the original source used to generate an HTML tag and content.
• Our class name has a suffix of TagHelper, which is not required, but it’s considered a best practice convention.
You could declare the class as:
public class Email : TagHelper

2. To make the EmailTagHelper class available to all our Razor views, we will add the addTagHelper
directive to the Views/_ViewImports.cshtml file:
@using AuthoringTagHelpers
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "*, AuthoringTagHelpers"

The code above uses the wildcard syntax to specify all the tag helpers in our assembly will be available. The first
string after @addTagHelper specifies the tag helper to load (we are using “*” for all tag helpers), and the second
string “AuthoringTagHelpers” specifies the assembly the tag helper is in. Also, note that the second line brings in
the ASP.NET Core MVC tag helpers using the wildcard syntax (those helpers are discussed in Introduction to Tag
Helpers.) It’s the @addTagHelper directive that makes the tag helper available to the Razor view. Alternatively,
you can provide the fully qualified name (FQN) of a tag helper as shown below:
@using AuthoringTagHelpers
@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
@addTagHelper "AuthoringTagHelpers.TagHelpers.EmailTagHelper, AuthoringTagHelpers"

To add a tag helper to a view using a FQN, you first add the FQN
(AuthoringTagHelpers.TagHelpers.EmailTagHelper), and then the assembly name (Authoring-
TagHelpers). Most developers will prefer to use the wildcard syntax. Introduction to Tag Helpers goes into detail on
tag helper adding, removing, hierarchy, and wildcard syntax.

1.5. MVC 279


ASP.NET 5 Documentation, Release

3. Update the markup in the Views/Home/Contact.cshtml file with these changes:


@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong><email>Support</email><br />
<strong>Marketing:</strong><email>Marketing</email>
</address>

4. Run the app and use your favorite browser to view the HTML source so you can verify that the email tags are
replaced with anchor markup (For example, <a>Support</a>). Support and Marketing are rendered as a
links, but they don’t have an href attribute to make them functional. We’ll fix that in the next section.
Note: Like HTML tags and attributes, tags, class names and attributes in Razor, and C# are not case-sensitive.

A working email Tag Helper In this section, we will update the EmailTagHelper so that it will create a valid
anchor tag for email. We’ll update our tag helper to take information from a Razor view (in the form of a mail-to
attribute) and use that in generating the anchor.
Update the EmailTagHelper class with the following:
public class EmailTagHelper : TagHelper
{
private const string EmailDomain = "contoso.com";

// Can be passed via <email mail-to="..." />.


// Pascal case gets translated into lower-kebab-case.
public string MailTo { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
output.TagName = "a"; // Replaces <email> with <a> tag

var address = MailTo + "@" + EmailDomain;


output.Attributes["href"] = "mailto:" + address;
output.Content.SetContent(address);
}
}

Notes:
• Pascal-cased class and property names for tag helpers are translated into their lower kebab case. Therefore, to
use the MailTo attribute, you’ll use <email mail-to="value"/> equivalent.
• The last line sets the completed content for our minimally functional tag helper.
• The following line shows the syntax for adding attributes:

280 Chapter 1. Topics


ASP.NET 5 Documentation, Release

public override void Process(TagHelperContext context, TagHelperOutput output)


{
output.TagName = "a"; // Replaces <email> with <a> tag

var address = MailTo + "@" + EmailDomain;


output.Attributes["href"] = "mailto:" + address;
output.Content.SetContent(address);
}

That approach works for the attribute “href” as long as it doesn’t currently exist in the attributes collection. You can
also use the output.Attributes.Add method to add a tag helper attribute to the end of the collection of tag
attributes.
3. Update the markup in the Views/Home/Contact.cshtml file with these changes:
@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong><email mail-to="Support"></email><br />
<strong>Marketing:</strong><email mail-to="Marketing"></email>
</address>

4. Run the app and verify that it generates the correct links.
Note: If you were to write the email tag self-closing (<email mail-to="Rick" />), the final output would also
be self-closing. To enable the ability to write the tag with only a start tag (<email mail-to="Rick">) you must
decorate the class with the following:
[TargetElement("email", TagStructure = TagStructure.WithoutEndTag)]

With a self-closing email tag helper, the output would be <a href="mailto:[email protected]" />. Self-
closing anchor tags are not valid HTML, so you wouldn’t want to create one, but you might want to create a tag helper
that is self-closing. Tag helpers set the type of the TagMode property after reading a tag.

An asynchronous email helper In this section we’ll write an asynchronous email helper.
1. Replace the EmailTagHelper class with the following code:
public class EmailTagHelper : TagHelper
{
private const string EmailDomain = "contoso.com";
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "a"; // Replaces <email> with <a> tag
var content = await output.GetChildContentAsync();
var target = content.GetContent() + "@" + EmailDomain;
output.Attributes["href"] = "mailto:" + target;
output.Content.SetContent(target);

1.5. MVC 281


ASP.NET 5 Documentation, Release

}
}

Notes:
• This version uses the asynchronous ProcessAsync method. The asynchronous GetChildContentAsync
returns a Task containing the TagHelperContent.
• We use the output parameter to get contents of the HTML element.
2. Make the following change to the Views/Home/Contact.cshtml file so the tag helper can get the target email.
@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong><email>Support</email><br />
<strong>Marketing:</strong><email>Marketing</email>
</address>

3. Run the app and verify that it generates valid email links.

The bold Tag Helper


1. Add the following BoldTagHelper class to the TagHelpers folder.
using Microsoft.AspNet.Razor.Runtime.TagHelpers;

namespace AuthoringTagHelpers.TagHelpers
{
[TargetElement(Attributes = "bold")]
public class BoldTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
output.Attributes.RemoveAll("bold");
output.PreContent.SetHtmlContent("<strong>");
output.PostContent.SetHtmlContent("</strong>");
}
}
}

Notes:
• The [HtmlTargetElement] attribute passes an attribute parameter that specifies that any HTML element
that contains an HTML attribute named “bold” will match, and the Process override method in the class will
run. In our sample, the Process method removes the “bold” attribute and surrounds the containing markup
with <strong></strong>.

282 Chapter 1. Topics


ASP.NET 5 Documentation, Release

• Because we don’t want to replace the existing tag content, we must write the opening <strong>
tag with the PreContent.SetHtmlContent method and the closing </strong> tag with the
PostContent.SetHtmlContent method.
2. Modify the About.cshtml view to contain a bold attribute value. The completed code is shown below.
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p bold>Use this area to provide additional information.</p>

<bold> Is this bold?</bold>

3. Run the app. You can use your favorite browser to inspect the source and verify that the markup has changed as
promised.
The [HtmlTargetElement] attribute above only targets HTML markup that provides an attribute name of “bold”.
The <bold> element was not modified by the tag helper.
4. Comment out the [HtmlTargetElement] attribute line and it will default to targeting <bold> tags, that
is, HTML markup of the form <bold>. Remember, the default naming convention will match the class name
BoldTagHelper to <bold> tags.
5. Run the app and verify that the <bold> tag is processed by the tag helper.
Decorating a class with multiple [HtmlTargetElement] attributes results in a logical-OR of the targets. For
example, using the code below, a bold tag or a bold attribute will match.
[TargetElement("bold")]
[TargetElement(Attributes = "bold")]

When multiple attributes are added to the same statement, the runtime treats them as a logical-AND. For example, in
the code below, an HTML element must be named “bold” with an attribute named “bold” ( <bold bold /> ) to match.
[HtmlTargetElement("bold", Attributes = "bold")]

You can also use the [HtmlTargetElement] to change the name of the targeted element. For example if you
wanted the BoldTagHelper to target <MyBold> tags, you would use the following attribute:
[HtmlTargetElement("MyBold")]

Web site information Tag Helper


1. Add a Models folder.
2. Add the following WebsiteContext class to the Models folder:
using System;

namespace AuthoringTagHelpers.Models
{
public class WebsiteContext
{
public Version Version { get; set; }
public int CopyrightYear { get; set; }
public bool Approved { get; set; }
public int TagsToShow { get; set; }

1.5. MVC 283


ASP.NET 5 Documentation, Release

}
}

3. Add the following WebsiteInformationTagHelper class to the TagHelpers folder.


using System;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using AuthoringTagHelpers.Models;

namespace AuthoringTagHelpers.TagHelpers
{
public class WebsiteInformationTagHelper : TagHelper
{
public WebsiteContext Info { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
output.TagName = "section";
output.Content.SetHtmlContent(
$@"<ul><li><strong>Version:</strong> {Info.Version}</li>
<li><strong>Copyright Year:</strong> {Info.CopyrightYear}</li>
<li><strong>Approved:</strong> {Info.Approved}</li>
<li><strong>Number of tags to show:</strong> {Info.TagsToShow}</li></ul>");
output.TagMode = TagMode.StartTagAndEndTag;
}
}
}

Notes:
• As mentioned previously, tag helpers translates Pascal-cased C# class names and properties for tag helpers
into lower kebab case. Therefore, to use the WebsiteInformationTagHelper in Razor, you’ll write
<website-information />.
• We are not explicitly identifying the target element with the [HtmlTargetElement] attribute, so the default
of website-information will be targeted. If you applied the following attribute (note it’s not kebab case
but matches the class name):
[HtmlTargetElement("WebsiteInformation")]

The lower kebab case tag <website-information /> would not match. If you want use the
[HtmlTargetElement] attribute, you would use kebab case as shown below:
[HtmlTargetElement("Website-Information")]

• Elements that are self-closing have no content. For this example, the Razor markup will use a self-closing
tag, but the tag helper will be creating a section element (which is not self-closing and we are writing content
inside the section element). Therefore, we need to set TagMode to StartTagAndEndTag to write output.
Alternatively, you can comment out the line setting TagMode and write markup with a closing tag. (Example
markup is provided later in this tutorial.)
• The $ (dollar sign) in the following line uses an interpolated string:
$@"<ul><li><strong>Version:</strong> {Info.Version}</li>

5. Add the following markup to the About.cshtml view. The highlighted markup displays the web site information.
@using AuthoringTagHelpers.Models
@{
ViewData["Title"] = "About";

284 Chapter 1. Topics


ASP.NET 5 Documentation, Release

}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<p bold>Use this area to provide additional information.</p>

<bold> Is this bold?</bold>

<h3> web site info </h3>


<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1790,
Approved = true,
TagsToShow = 131 }" />

Note: In the Razor markup shown below:


<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1790,
Approved = true,
TagsToShow = 131 }" />

Razor knows the info attribute is a class, not a string, and you want to write C# code. Any non-string tag helper
attribute should be written without the @ character.
6. Run the app, and navigate to the About view to see the web site information.
Note:
• You can use the following markup with a closing tag and remove the line with
TagMode.StartTagAndEndTag in the tag helper:
<website-information info="new WebsiteContext {
Version = new Version(1, 3),
CopyrightYear = 1790,
Approved = true,
TagsToShow = 131 }" >
</website-information>

Condition Tag Helper The condition tag helper renders output when passed a true value.
1. Add the following ConditionTagHelper class to the TagHelpers folder.
using Microsoft.AspNet.Razor.Runtime.TagHelpers;

namespace AuthoringTagHelpers.TagHelpers
{
[TargetElement(Attributes = nameof(Condition))]
public class ConditionTagHelper : TagHelper
{
public bool Condition { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
if (!Condition)
{
output.SuppressOutput();
}

1.5. MVC 285


ASP.NET 5 Documentation, Release

}
}
}

2. Replace the contents of the Views/Home/Index.cshtml file with the following markup:
@using AuthoringTagHelpers.Models
@model WebsiteContext

@{
ViewData["Title"] = "Home Page";
}

<div>
<h3>Information about our website (outdated):</h3>
<Website-InforMation info=Model />
<div condition="Model.Approved">
<p>
This website has <strong surround="em"> @Model.Approved </strong> been approved yet.
Visit www.contoso.com for more information.
</p>
</div>
</div>

3. Replace the Index method in the Home controller with the following code:
public IActionResult Index(bool approved = false)
{
return View(new WebsiteContext
{
Approved = approved,
CopyrightYear = 2015,
Version = new Version(1, 3, 3, 7),
TagsToShow = 20
});
}

4. Run the app and browse to the home page. The markup in the conditional div will not be rendered. Append the
query string ?approved=true to the URL (for example, http://localhost:1235/Home/Index?approved=true).
The approved is set to true and the conditional markup will be displayed.
Note: We use the nameof operator to specify the attribute to target rather than specifying a string as we did with the
bold tag helper:
[TargetElement(Attributes = nameof(Condition))]
// [TargetElement(Attributes = "condition")]
public class ConditionTagHelper : TagHelper
{
public bool Condition { get; set; }

public override void Process(TagHelperContext context, TagHelperOutput output)


{
if (!Condition)
{
output.SuppressOutput();
}
}
}

286 Chapter 1. Topics


ASP.NET 5 Documentation, Release

The nameof operator will protect the code should it ever be refactored (we might want to change the name to RedCon-
dition).

Avoiding Tag Helper conflicts In this section, we will write a pair of auto-linking tag helpers. The first will replace
markup containing a URL starting with HTTP to an HTML anchor tag containing the same URL (and thus yielding a
link to the URL). The second will do the same for a URL starting with WWW.
Because these two helpers are closely related and we may refactor them in the future, we’ll keep them in the same file.
1. Add the following AutoLinker class to the TagHelpers folder.
[TargetElement("p")]
public class AutoLinkerHttpTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync();
// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent.GetContent(),
@"\b(?:https?://)(\S+)\b",
"<a target=\"_blank\" href=\"$0\">$0</a>")); // http link version}
}
}

Notes: The AutoLinkerHttpTagHelper class targets p elements and uses Regex to create the anchor.
2. Add the following markup to the end of the Views/Home/Contact.cshtml file:
@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong><email>Support</email><br />
<strong>Marketing:</strong><email>Marketing</email>
</address>

<p>Visit us at http://docs.asp.net or at www.microsoft.com</p>

3. Run the app and verify that the tag helper renders the anchor correctly.
4. Update the AutoLinker class to include the AutoLinkerWwwTagHelper which will convert www text
to an anchor tag that also contains the original www text. The updated code is highlighted below:
[TargetElement("p")]
public class AutoLinkerHttpTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync();

1.5. MVC 287


ASP.NET 5 Documentation, Release

// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent.GetContent(),
@"\b(?:https?://)(\S+)\b",
"<a target=\"_blank\" href=\"$0\">$0</a>")); // http link version}
}
}

[TargetElement("p")]
public class AutoLinkerWwwTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = await output.GetChildContentAsync();
// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent.GetContent(),
@"\b(www\.)(\S+)\b",
"<a target=\"_blank\" href=\"http://$0\">$0</a>")); // www version
}
}

5. Run the app. Notice the www text is rendered as a link but the HTTP text is not. If you put a break point in
both classes, you can see that the HTTP tag helper class runs first. Later in the tutorial we’ll see how to control
the order that tag helpers run in. The problem is that the tag helper output is cached, and when the WWW tag
helper is run, it overwrites the cached output from the HTTP tag helper. We’ll fix that with the following code:
public class AutoLinkerHttpTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent();

// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent,
@"\b(?:https?://)(\S+)\b",
"<a target=\"_blank\" href=\"$0\">$0</a>")); // http link version}
}
}

[TargetElement("p")]
public class AutoLinkerWwwTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent();

// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent,
@"\b(www\.)(\S+)\b",
"<a target=\"_blank\" href=\"http://$0\">$0</a>")); // www version
}
}
}

288 Chapter 1. Topics


ASP.NET 5 Documentation, Release

Note: In the first edition of the auto-linking tag helpers, we got the content of the target with the following code:
var childContent = await output.GetChildContentAsync();

That is, we call GetChildContentAsync using the TagHelperOutput passed into the ProcessAsync
method. As mentioned previously, because the output is cached, the last tag helper to run wins. We fixed that problem
with the following code:
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent();

The code above checks to see if the content has been modified, and if it has, it gets the content from the output buffer.
7. Run the app and verify that the two links work as expected. While it might appear our auto linker tag helper
is correct and complete, it has a subtle problem. If the WWW tag helper runs first, the www links will not be
correct. Update the code by adding the Order overload to control the order that the tag runs in. The Order
property determines the execution order relative to other tag helpers targeting the same element. The default
order value is zero and instances with lower values are executed first.
public class AutoLinkerHttpTagHelper : TagHelper
{
// This filter must run before the AutoLinkerWwwTagHelper as it searches and replaces http and
// the AutoLinkerWwwTagHelper adds http to the markup.
public override int Order
{
get { return int.MinValue; }
}

The above code will guarantee that the HTTP tag helper runs before the WWW tag helper. Change Order to
MaxValue and verify that the markup generated for the WWW tag is incorrect.

Inspecting and retrieving child content The tag-helpers provide several properties to retrieve content.
• The result of GetChildContentAsync can be appended to output.Content.
• You can inspect the result of GetChildContentAsync with GetContent.
• If you modify output.Content, the TagHelper body will not be executed or rendered unless you call
GetChildContentAsync as in our auto-linker sample:
public class AutoLinkerHttpTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
var childContent = output.Content.IsModified ? output.Content.GetContent() :
(await output.GetChildContentAsync()).GetContent();

// Find Urls in the content and replace them with their anchor tag equivalent.
output.Content.SetHtmlContent(Regex.Replace(
childContent,
@"\b(?:https?://)(\S+)\b",
"<a target=\"_blank\" href=\"$0\">$0</a>")); // http link version}
}
}

• Multiple calls to GetChildContentAsync will return the same value and will not re-execute the
TagHelper body unless you pass in a false parameter indicating not use the cached result.

1.5. MVC 289


ASP.NET 5 Documentation, Release

Advanced Tag Helpers

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Partial Views

Note: We are currently working on this topic.


We welcome your input to help shape the scope and approach. You can track the status and provide input on this issue
at GitHub.
If you would like to review early drafts and outlines of this topic, please leave a note with your contact information in
the issue.
Learn more about how you can contribute on GitHub.

Injecting Services Into Views

By Steve Smith
ASP.NET Core supports dependency injection into views. This can be useful for view-specific services, such as
localization or data required only for populating view elements. You should try to maintain separation of concerns
between your controllers and views. Most of the data your views display should be passed in from the controller.

Sections:
• A Simple Example
• Populating Lookup Data
• Overriding Services
• See Also

View or download sample code