Live
Live
Introduction
Getting Started
Your first ASP.NET Core application on a Mac using Visual Studio Code
Building your first ASP.NET Core MVC app with Visual Studio
Developing ASP.NET Core applications using dotnet watch
Tutorials
Fundamentals
Application Startup
Middleware
Working with Static Files
Routing
URL Rewriting Middleware
Error Handling
Globalization and localization
Configuration
Logging
File Providers
Dependency Injection
Working with Multiple Environments
Hosting
Session and application state
Servers
Kestrel
ASP.NET Core Module
WebListener
Request Features
Open Web Interface for .NET (OWIN)
Choose between ASP.NET Core and ASP.NET
Choose between .NET Core and .NET Framework runtime
MVC
Building your first ASP.NET Core MVC app with Visual Studio
Getting started
Adding a controller
Adding a view
Adding a model
Working with SQL Server LocalDB
Controller methods and views
Adding Search
Adding a New Field
Adding Validation
Examining the Details and Delete methods
Building your first Web API with ASP.NET Core MVC
Getting started with ASP.NET Core MVC and Entity Framework Core
Getting started
Create, Read, Update, and Delete operations
Sorting, filtering, paging, and grouping
Migrations
Creating a complex data model
Reading related data
Updating related data
Handling concurrency conflicts
Inheritance
Advanced topics
Creating backend services for native mobile applications
Handling requests with controllers
Routing to controller actions
Model binding
Model validation
File uploads
Dependency injection into controllers
Testing controllers
Rendering HTML with views
Razor syntax
View compilation
Layout
HTML helpers
Tag helpers
Partial views
Dependency injection into views
View components
Building Web APIs
Building your first Web API with ASP.NET Core MVC using Visual Studio
ASP.NET Web API Help Pages using Swagger
Creating backend services for native mobile applications
Formatting response data
Support resource updates with JSON patch
Filters
Areas
Advanced
Working with the Application Model
Application parts
Creating a Custom View Engine
Custom formatters
Testing
Unit testing
Integration testing
Testing controllers
Working with Data
Getting started with ASP.NET Core and Entity Framework Core using Visual Studio
ASP.NET Core with EF Core - new database
ASP.NET Core with EF Core - existing database
Getting Started with ASP.NET Core and Entity Framework 6
Azure Storage
Adding Azure Storage by using Visual Studio Connected Services
Get started with Blob storage and Visual Studio Connected Services
Get Started with Queue Storage and Visual Studio Connected Services
Get Started with Table Storage and Visual Studio Connected Services
Client-Side Development
Using Gulp
Using Grunt
Manage client-side packages with Bower
Building beautiful, responsive sites with Bootstrap
Knockout.js MVVM Framework
Using Angular for Single Page Applications (SPAs)
Styling applications with Less, Sass, and Font Awesome
Bundling and minification
Working with a Content Delivery Network (CDN)
Building Projects with Yeoman
Using Browser Link
Mobile
Creating Backend Services for Native Mobile Applications
Publishing and Deployment
Publishing to IIS
How Web Publishing In Visual Studio Works
Deploy an ASP.NET Core web app to Azure using Visual Studio
Publishing to an Azure Web App with Continuous Deployment
Publishing to a Windows Virtual Machine on Azure
Publish to a Docker Image
Publish to a Linux Production Environment using nginx
Use VSTS to Build and Publish to an Azure Web App with Continuous Deployment
Using Apache Web Server on CentOS as a reverse-proxy
ASP.NET Core on Nano Server
ASP.NET Core and Azure Service Fabric
Guidance for Hosting Providers
ASP.NET Core Module configuration reference
Using IIS Modules with ASP.NET Core
Directory structure
Servicing
Data Protection
Security
Authentication
Introduction to Identity
Configure Identity
Enabling authentication using Facebook, Google and other external providers
Account Confirmation and Password Recovery
Two-factor authentication with SMS
Supporting Third Party Clients using OAuth 2.0
Using Cookie Middleware without ASP.NET Core Identity
Azure Active Directory
Securing ASP.NET Core apps with IdentityServer4
Authorization
Introduction
Simple Authorization
Role based Authorization
Claims-Based Authorization
Custom Policy-Based Authorization
Dependency Injection in requirement handlers
Resource Based Authorization
View Based Authorization
Limiting identity by scheme
Data Protection
Introduction to Data Protection
Getting Started with the Data Protection APIs
Consumer APIs
Configuration
Extensibility APIs
Implementation
Compatibility
Enforcing SSL
Safe storage of app secrets during development
Azure Key Vault configuration provider
Anti-Request Forgery
Preventing Open Redirect Attacks
Preventing Cross-Site Scripting
Enabling Cross-Origin Requests (CORS)
Performance
Measuring Application Performance
Caching
In Memory Caching
Working with a Distributed Cache
Response Caching
Response Caching Middleware
Response Compression Middleware
Migration
Migrating From ASP.NET MVC to ASP.NET Core MVC
Migrating Configuration
Migrating Authentication and Identity
Migrating from ASP.NET Web API
Migrating HTTP Modules to Middleware
API Reference
What's new
All release notes
Contribute
Introduction to ASP.NET Core
3/3/2017 2 min to read Edit on GitHub
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.
Next steps
For getting-started tutorials, see ASP.NET Core Tutorials
For in-depth introduction to ASP.NET Core concepts and architecture, see ASP.NET Core Fundamentals.
An ASP.NET Core app can use the .NET Core or .NET Framework runtime. For more information, see Choosing
between .NET Core and .NET Framework.
Getting Started with ASP.NET Core
3/8/2017 1 min to read Edit on GitHub
mkdir aspnetcoreapp
cd aspnetcoreapp
dotnet new web
dotnet restore
4. Run the app (the dotnet run command will build the app when it's out of date):
dotnet run
5. Browse to http://localhost:5000
Next steps
For more getting-started tutorials, see ASP.NET Core Tutorials
For an introduction to ASP.NET Core concepts and architecture, see ASP.NET Core Introduction and ASP.NET Core
Fundamentals.
An ASP.NET Core app can use the .NET Core or .NET Framework runtime. For more information, see Choosing
between .NET Core and .NET Framework.
Build an ASP.NET Core app on a Mac or Linux using
Visual Studio Code
3/15/2017 4 min to read Edit on GitHub
This article will show you how to write your first ASP.NET Core application on macOS or Linux.
When the CLI command completes; the following output and files are produced.
Startup.cs : Startup Class - class configures the request pipeline that handles all requests made to the
application.
Program.cs : Program Class that contains the Main entry point of the application.
firstapp.csproj : Project file MSBuild Project file format for ASP.NET Core applications. Contains Project to
Project references, NuGet References and other project related items.
appsettings.json / appsettings.Development.json : Environment base app settings configuration file. See
Configuration.
bower.json : Bower package dependencies for the project.
.bowerrc : Bower configuration file which defines where to install the components when Bower downloads the
assets.
bundleconfig.json : configuration files for bundling and minifying front-end JavaScript and CSS assets.
Views : Contains the Razor views. Views are the components that display the app's user interface (UI). Generally,
this UI displays the model data.
Controllers : Contains MVC Controllers, initially HomeController.cs. Controllers are classes that handle browser
requests.
wwwroot : Web application root folder.
For more information see The MVC pattern.
For Restore, alternately, you can run dotnet restore from the terminal or enter P or Ctrl+Shift+P in VS
Code and then type .NET as shown:
VS Code provides a streamlined, clean interface for working with files and a productive coding enviromment.
In the left navigation bar, there are five icons, representing four viewlets:
Explore
Search
Git
Debug
Extensions
The Explorer viewlet provides folder navigation and a view of the files you have open. It displays a badge to
indicate files with unsaved changes. You can create new folders and files in the viewlet. You can select Save All
from a menu option that appears on mouse over.
The Search viewlet allows you to search the folder tree of files you have open. The search is for filenames and file
contents.
VS Code will integrate with Git if it is installed on your system. You can initialize a new repository, make commits,
and push changes from the Git viewlet.
To stop the application, close the browser and hit the "Stop" icon on the debug bar
Using the dotnet commands
Run dotnet run command to launch the app from terminal/bash
Navigate to http://localhost:5000
Publishing to Azure
VS Code provides Git integration 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.
Add a commit message and tap enter or tap the checkmark icon to commit the staged files.
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.
If you don't have an Azure account, you can create a free trial.
Create a Web App in the Azure Portal to host your new application.
Configure the Web App in Azure to support continuous deployment using Git.
Record the Git URL for the Web App from the Azure portal.
In a Terminal window, add a remote named azure with the Git URL you noted previously.
git remote add azure https://[email protected]:443/MyFirstAppMac.git
Looking at the Deployment Details in the Azure Portal, you can see the logs and steps each time there is a commit
to the branch.
Additional resources
Visual Studio Code
Fundamentals
Building your first ASP.NET Core MVC app with Visual
Studio
3/3/2017 1 min to read Edit on GitHub
This series of tutorials will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio.
1. Getting started
2. Adding a controller
3. Adding a view
4. Adding a model
5. Working with SQL Server LocalDB
6. Controller methods and views
7. Adding Search
8. Adding a New Field
9. Adding Validation
10. Examining the Details and Delete methods
Developing ASP.NET Core apps using dotnet watch
3/14/2017 2 min to read Edit on GitHub
The console output will show messages similar to the following (indicating that the app is running and waiting for
requests):
$ dotnet run
Hosting environment: Production
Content root path: C:/Docs/aspnetcore/tutorials/dotnet-watch/sample/WebApp
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
</ItemGroup>
Run dotnet watch run in the WebApp folder. The console output will indicate watch has started.
Save the file. The console output will show messages indicating that `dotnet watch` detected a file change and
restarted the app.
- Change the `Product` method of the `MathController` back to returning the sum and save the file.
- In a command window, naviagate to the `WebAppTests` folder.
- Run `dotnet restore`
- Run `dotnet watch test`. You see output indicating that a test failed and that watcher is waiting for file
changes:
```console
Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.
Test Run Failed.
Fix the Product method code so it returns the product. Save the file.
dotnet watch detects the file change and reruns the tests. The console output will show the tests passed.
dotnet-watch in GitHub
dotnet-watch is part of the GitHub DotNetTools repository.
The MSBuild section of the dotnet-watch ReadMe explains how dotnet-watch can be configured from the MSBuild
project file being watched. The dotnet-watch ReadMe contains information on dotnet-watch not covered in this
tutorial.
ASP.NET Core tutorials
3/17/2017 1 min to read Edit on GitHub
The following step-by-step guides for developing ASP.NET Core applications are available:
Client-side development
Using Gulp
Using Grunt
Manage client-side packages with Bower
Building beautiful, responsive sites with Bootstrap
Testing
Unit Testing in .NET Core using dotnet test
An ASP.NET Core app is simply a console app that creates a web server in its Main method:
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();
}
}
}
Main uses WebHostBuilder , which follows the builder pattern, to create a web application host. The builder has
methods that define the web server (for example UseKestrel ) and the startup class ( UseStartup ). In the example
above, the Kestrel web server is used, but other web servers can be specified. We'll show more about UseStartup
in the next section. WebHostBuilder provides many optional methods, including UseIISIntegration for hosting in
IIS and IIS Express, and UseContentRoot for specifying the root content directory. The Build and Run methods
build the IWebHost object that will host the app and start it listening for incoming HTTP requests.
Startup
The UseStartup method on WebHostBuilder specifies the Startup class for your app.
host.Run();
}
}
The Startup class is where you define the request handling pipeline and where any services needed by the app
are configured. The Startup class must be public and contain the following methods:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
}
ConfigureServicesdefines the services (see Services below) used by your app (such as the ASP.NET MVC
Core framework, Entity Framework Core, Identity, etc.)
Configure defines the middleware in the request pipeline
For more information, see Application startup.
Services
A service is a component that is intended for common consumption in an application. Services are made available
through dependency injection (DI). ASP.NET Core includes a simple built-in inversion of control (IoC) container
that supports constructor injection by default. The built-in container can be easily replaced with your container of
choice. In addition to its loose coupling benefit, DI makes services available throughout your app. For example,
logging is available throughout your app.
For more information, see Dependency injection .
Middleware
In ASP.NET Core you compose your request pipeline using Middleware. ASP.NET Core middleware performs
asynchronous logic on an HttpContext and then either invokes the next middleware in the sequence or
terminates the request directly. You generally "Use" middleware by taking a dependency on a NuGet package and
invoking a corresponding UseXYZ extension method on the IApplicationBuilder in the Configure method.
ASP.NET Core comes with a rich set of built-in middleware:
Static files
Routing
Authentication
You can use any OWIN-based middleware with ASP.NET Core, and you can write your own custom middleware.
For more information, see Middleware and Open Web Interface for .NET (OWIN).
Servers
The ASP.NET Core hosting model does not directly listen for requests; rather it relies on an HTTP server
implementation to forward the request to the application. The forwarded request is wrapped as a set of feature
interfaces that the application then composes 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.
For more information, see Servers and Hosting.
Content root
The content root is the base path to any content used by the app, such as its views and web content. By default the
content root is the same as application base path for the executable hosting the app; an alternative location can be
specified with WebHostBuilder.
Web root
The web root of your app is the directory in your project for public, static resources like css, js, and image files. The
static files middleware will only serve files from the web root directory (and sub-directories) by default. The web
root path defaults to /wwwroot, but you can specify a different location using the WebHostBuilder.
Configuration
ASP.NET Core uses a new configuration model for handling simple name-value pairs. The new configuration
model is not based on System.Configuration or web.config; rather, it pulls from an ordered set of configuration
providers. The built-in configuration providers support a variety of file formats (XML, JSON, INI) and environment
variables to enable environment-based configuration. You can also write your own custom configuration
providers.
For more information, see Configuration.
Environments
Environments, like "Development" and "Production", are a first-class notion in ASP.NET Core and can be set using
environment variables.
For more information, see Working with Multiple Environments.
Additional information
See also the following topics:
Logging
Error Handling
Globalization and localization
File Providers
Managing Application State
Application Startup in ASP.NET Core
3/3/2017 2 min to read Edit on GitHub
The Startup class must include a Configure method and can optionally include a ConfigureServices method,
both of which are called when the application starts. The class can also include environment-specific versions of
these methods.
Learn about handling exceptions during application startup.
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
Each Use extension method adds a middleware component 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.
For more information about how to use IApplicationBuilder , see Middleware.
Additional services, like IHostingEnvironment and ILoggerFactory may also be specified in the method signature,
in which case these services will be injected if they are available.
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
Adding services to the services container makes them available within your application via dependency injection.
Additional Resources
Working with Multiple Environments
Middleware
Logging
Configuration
ASP.NET Core Middleware Fundamentals
3/3/2017 8 min to read Edit on GitHub
What is middleware
Middleware is software that is 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 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
instance that is passed into the Configure method in the Startup class. An individual request delegate can be
specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class.
These reusable classes and in-line anonymous methods 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.
Each delegate can perform operations before and after the next delegate. A delegate can also decide to not
pass a request to the next delegate, which is called short-circuiting the request pipeline. Short-circuiting is
often desirable because it allows unnecessary work to be avoided. For example, the static file middleware can
return a request for a static file and short-circuit the rest of the pipeline. Exception-handling delegates need to
be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.
The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case
doesn't include an actual request pipeline. Instead, a single anonymous function is called in response to every
HTTP request.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
WARNING
Be careful modifying the HttpResponse after invoking next , because the response may have already been sent to the
client. You can use HttpResponse.HasStarted to check whether the headers have been sent.
WARNING
Do not call next.Invoke after calling a write method. A middleware component either produces a response or calls
next.Invoke , but not both.
Ordering
The order that middleware components are added in the Configure method defines the order in which they
are invoked on requests, and the reverse order for the response. This ordering is critical for security,
performance, and functionality.
The Configure method (shown below) adds the following middleware components:
1. Exception/error handling
2. Static file server
3. Authentication
4. MVC
In the code above, UseExceptionHandler is the first middleware component added to the pipelinetherefore, it
catches any exceptions that occur in later calls.
The static file middleware is called early in the pipeline so it can handle requests and short-circuit without
going through the remaining components. The static file middleware provides no authorization checks. Any
files served by it, including those under wwwroot, are publicly available. See Working with static files for an
approach to secure static files.
If the request is not handled by the static file middleware, it's passed on to the Identity middleware (
app.UseIdentity ), which performs authentication. Identity does not short-circuit unauthenticated requests.
Although Identity authenticates requests, authorization (and rejection) occurs only after MVC selects a specific
controller and action.
The following example demonstrates a middleware ordering where requests for static files are handled by the
static file middleware before the response compression middleware. Static files are not compressed with this
ordering of the middleware. The MVC responses from UseMvcWithDefaultRoute can be compressed.
app.Map("/map2", HandleMapTest2);
The following table shows the requests and responses from http://localhost:1234 using the previous code:
REQUEST RESPONSE
When Map is used, the matched path segment(s) are removed from HttpRequest.Path and appended to
HttpRequest.PathBase for each request.
MapWhen branches the request pipeline based on the result of the given predicate. 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 predicate is used to detect the presence of a query string variable branch :
public class Startup
{
private static void HandleBranch(IApplicationBuilder app)
{
app.Run(async context =>
{
var branchVer = context.Request.Query["branch"];
await context.Response.WriteAsync($"Branch used = {branchVer}");
});
}
The following table shows the requests and responses from http://localhost:1234 using the previous code:
REQUEST RESPONSE
app.Map("/level1/level2", HandleMultiSeg);
Built-in middleware
ASP.NET Core ships with the following middleware components:
MIDDLEWARE DESCRIPTION
Static Files Provides support for serving static files and directory
browsing.
URL Rewriting Middleware Provides support for rewriting URLs and redirecting
requests.
Writing middleware
Middleware is generally encapsulated in a class and exposed with an extension method. Consider the following
middleware, which sets the culture for the current request from the query string:
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
}
}
}
Note: The sample code above is used to demonstrate creating a middleware component. See Globalization and
localization for ASP.NET Core's built-in localization support.
You can test the middleware by passing in the culture, for example http://localhost:7997/?culture=no .
The following code moves the middleware delegate to a class:
using Microsoft.AspNetCore.Http;
using System.Globalization;
using System.Threading.Tasks;
namespace Culture
{
public class RequestCultureMiddleware
{
private readonly RequestDelegate _next;
CultureInfo.CurrentCulture = culture;
CultureInfo.CurrentUICulture = culture;
using Microsoft.AspNetCore.Builder;
namespace Culture
{
public static class RequestCultureMiddlewareExtensions
{
public static IApplicationBuilder UseRequestCulture(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<RequestCultureMiddleware>();
}
}
}
}
}
Middleware should follow the Explicit Dependencies Principle by exposing its dependencies in its constructor.
Middleware is constructed once per application lifetime. See Per-request dependencies below if you need to
share services with middleware within a request.
Middleware components can resolve their dependencies from dependency injection through constructor
parameters. UseMiddleware<T> can also accept additional parameters directly.
Per-request dependencies
Because middleware is constructed at app startup, not per-request, scoped lifetime services used by
middleware constructors are not shared with other dependency-injected types during each request. If you
must share a scoped service between your middleware and other types, add these services to the Invoke
method's signature. The Invoke method can accept additional parameters that are populated by dependency
injection. For example:
Resources
Sample code used in this doc
Migrating HTTP Modules to Middleware
Application Startup
Request Features
Introduction to working with static files in ASP.NET
Core
3/7/2017 7 min to read Edit on GitHub
By Rick Anderson
Static files, such as HTML, CSS, image, and JavaScript, are assets that an ASP.NET Core app can serve directly to
clients.
View or download sample code
host.Run();
}
Static files can be stored in any folder under the web root 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 wwwroot folder - css, images, and js. The URI to access an image in the images subfolder:
http://<app>/images/<imageFileName>
http://localhost:9189/images/banner3.svg
In order for static files to be served, you must configure the Middleware to add static files to the pipeline. The
static file 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 :
app.UseStaticFiles(); makes the files in web root (wwwroot by default) servable. Later I'll show how to make
other directory contents servable with UseStaticFiles .
You must include the NuGet package "Microsoft.AspNetCore.StaticFiles".
NOTE
web root defaults to the wwwroot directory, but you can set the web root directory with UseWebRoot .
Suppose you have a project hierarchy where the static files you wish to serve are outside the web root . For
example:
wwwroot
css
images
...
MyStaticFiles
test.png
For a request to access test.png, configure the static files middleware as follows:
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles")
});
}
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
}
And add required services by calling AddDirectoryBrowser extension method from Startup.ConfigureServices :
The code above allows directory browsing of the wwwroot/images folder using the URL http://<app>/MyImages,
with links to each file and folder:
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
}
NOTE
UseDefaultFiles must be called before UseStaticFiles to serve the default file. UseDefaultFiles is a URL re-writer
that doesn't actually serve the file. You must enable the static file middleware ( UseStaticFiles ) to serve the file.
UseFileServer
UseFileServer combines the functionality of UseStaticFiles , UseDefaultFiles , and UseDirectoryBrowser .
The following code enables static files and the default file to be served, but does not allow directory browsing:
app.UseFileServer();
The following code enables static files, default files and directory browsing:
app.UseFileServer(enableDirectoryBrowsing: true);
See Considerations on the security risks when enabling browsing. As with UseStaticFiles , UseDefaultFiles , and
UseDirectoryBrowser , if you wish to serve files that exist outside the web root , you instantiate and configure an
FileServerOptions object that you pass as a parameter to UseFileServer . For example, given the following
directory hierarchy in your Web app:
wwwroot
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
FileServerOptions .
app.UseFileServer(new FileServerOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
RequestPath = new PathString("/StaticFiles"),
EnableDirectoryBrowsing = true
});
}
If enableDirectoryBrowsingis set to true you are required to call AddDirectoryBrowser extension method from
Startup.ConfigureServices :
URI RESPONSE
http://<app>/StaticFiles/test.png MyStaticFiles/test.png
http://<app>/StaticFiles MyStaticFiles/default.html
If no default named files are in the MyStaticFiles directory, http://<app>/StaticFiles returns the directory listing
with clickable links:
NOTE
UseDefaultFiles and UseDirectoryBrowser will take the url http://<app>/StaticFiles without the trailing slash and
cause a client side redirect to http://<app>/StaticFiles/ (adding the trailing slash). Without the trailing slash relative URLs
within the documents would be incorrect.
FileExtensionContentTypeProvider
The FileExtensionContentTypeProvider class contains a collection that maps file extensions to MIME content types.
In the following sample, several file extensions are registered to known MIME types, the ".rtf" is replaced, and
".mp4" is removed.
public void Configure(IApplicationBuilder app)
{
// Set up custom content types -associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages"),
ContentTypeProvider = provider
});
app.UseDirectoryBrowser(new DirectoryBrowserOptions()
{
FileProvider = new PhysicalFileProvider(
Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
RequestPath = new PathString("/MyImages")
});
}
With the code above, a request for a file with an unknown content type will be returned as an image.
WARNING
Enabling ServeUnknownFileTypes is a security risk and using it is discouraged. FileExtensionContentTypeProvider
(explained below) provides a safer alternative to serving files with non-standard extensions.
Considerations
WARNING
UseDirectoryBrowser and UseStaticFiles can leak secrets. We recommend that you not enable directory browsing in
production. Be careful about which directories you enable with UseStaticFiles or UseDirectoryBrowser as the entire
directory and all sub-directories will be accessible. We recommend keeping public content in its own directory such as
<content root>/wwwroot, away from application views, configuration files, etc.
The URLs for content exposed with UseDirectoryBrowser and UseStaticFiles are subject to the case
sensitivity and character restrictions of their underlying file system. For example, Windows is case
insensitive, but Mac and Linux are not.
ASP.NET Core applications hosted in IIS use the ASP.NET Core Module to forward all requests to the
application including requests for static files. The IIS static file handler is not used because it doesn't get a
chance to handle requests before they are handled by the ASP.NET Core Module.
To remove the IIS static file handler (at the server or website level):
Navigate to the Modules feature
Select StaticFileModule in the list
Tap Remove in the Actions sidebar
WARNING
If the IIS static file handler is enabled and the ASP.NET Core Module (ANCM) is not correctly configured (for example if
web.config was not deployed), static files will be served.
Code files (including c# and Razor) should be placed outside of the app project's web root (wwwroot by
default). This creates a clean separation between your app's client side content and server side source code,
which prevents server side code from being leaked.
Additional Resources
Middleware
Introduction to ASP.NET Core
Routing in ASP.NET Core
3/20/2017 19 min to read Edit on GitHub
IMPORTANT
This document covers the low level ASP.NET Core routing. For ASP.NET Core MVC routing, see Routing to Controller
Actions
Routing basics
Routing uses routes (implementations of IRouter to:
map incoming requests to route handlers
generate URLs used in responses
Generally, an app has a single collection of routes. When a request arrives, the route collection is processed in
order. The incoming request looks for a route that matches the request URL by calling the RouteAsync method
on each available route in the route collection. By contrast, a response can use routing to generate URLs (for
example, for redirection or links) based on route information, and thus avoid having to hard-code URLs, which
helps maintainability.
Routing is connected to the middleware pipeline by the RouterMiddleware class. ASP.NET MVC adds routing to
the middleware pipeline as part of its configuration. To learn about using routing as a standalone component,
see using-routing-middleware.
URL matching
URL matching is the process by which routing dispatches an incoming request to a handler. This process is
generally based on data in the URL path, but can be extended to consider any data in the request. The ability to
dispatch requests to separate handlers is key to scaling the size and complexity of an application.
Incoming requests enter the RouterMiddleware , which calls the RouteAsync method on each route in sequence.
The IRouter instance chooses whether to handle the request by setting the RouteContext Handler to a non-null
RequestDelegate . If a route sets a handler for the request, route processing stops and the handler will be invoked
to process the request. If all routes are tried and no handler is found for the request, the middleware calls next
and the next middleware in the request pipeline is invoked.
The primary input to RouteAsync is the RouteContext HttpContext associated with the current request. The
RouteContext.Handler and RouteContext RouteData are outputs that will be set after a route matches.
A match during RouteAsync will also set the properties of the RouteContext.RouteData to appropriate values
based on the request processing done so far. If a route matches a request, the RouteContext.RouteData will
contain important state information about the result.
RouteData is a dictionary of route values produced from the route. These values are usually determined
Values
by tokenizing the URL, and can be used to accept user input, or to make further dispatching decisions inside the
application.
RouteData DataTokens is a property bag of additional data related to the matched route. DataTokens are
provided to support associating state data with each route so the application can make decisions later based on
which route matched. These values are developer-defined and do not affect the behavior of routing in any way.
Additionally, values stashed in data tokens can be of any type, in contrast to route values, which must be easily
convertible to and from strings.
RouteData Routers is a list of the routes that took part in successfully matching the request. Routes can be
nested inside one another, and the Routers property reflects the path through the logical tree of routes that
resulted in a match. Generally the first item in Routers is the route collection, and should be used for URL
generation. The last item in Routers is the route that matched.
URL generation
URL generation is the process by which routing can create a URL path based on a set of route values. This allows
for a logical separation between your handlers and the URLs that access them.
URL generation follows a similar iterative process, but starts with user or framework code calling into the
GetVirtualPath method of the route collection. Each route will then have its GetVirtualPath method called in
sequence until a non-null VirtualPathData is returned.
The primary inputs to GetVirtualPath are:
VirtualPathContext HttpContext
VirtualPathContext Values
VirtualPathContext AmbientValues
Routes primarily use the route values provided by the Values and AmbientValues to decide where it is possible
to generate a URL and what values to include. The AmbientValues are the set of route values that were produced
from matching the current request with the routing system. In contrast, Values are the route values that specify
how to generate the desired URL for the current operation. The HttpContext is provided in case a route needs to
get services or additional data associated with the current context.
TIP
Think of Values as being a set of overrides for the AmbientValues . URL generation tries to reuse route values from the
current request to make it easy to generate URLs for links using the same route or route values.
NOTE
MapRoute doesn't take a route handler 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 example, ASP.NET MVC is typically
configured as a default handler that only handles requests that match an available controller and action. To learn more
about routing to MVC, see Routing to Controller Actions.
This is an example of a MapRoute call used by a typical ASP.NET MVC route definition:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
This template will match a URL path like and extract the route values
/Products/Details/17
{ controller = Products, action = Details, id = 17 } . The route values are determined by splitting the URL
path into segments, and matching each segment with the route parameter name in the route template. Route
parameters are named. They are defined by enclosing the parameter name in braces { } .
The template above could also match the URL path / and would produce the values
{ controller = Home, action = Index } . This happens because the {controller} and {action} route
parameters have default values, and the id route parameter is optional. An equals = sign followed by a value
after the route parameter name defines a default value for the parameter. A question mark ? after the route
parameter name defines the parameter as optional. Route parameters with a default value always produce a
route value when the route matches - optional parameters will not produce a route value if there was no
corresponding URL path segment.
See route-template-reference for a thorough description of route template features and syntax.
This example includes a route constraint:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id:int}");
This template will match a URL path like /Products/Details/17 , but not /Products/Details/Apples . The route
parameter definition {id:int} defines a route constraint for the id route parameter. Route constraints
implement IRouteConstraint and inspect route values to verify them. In this example the route value id must
be convertible to an integer. See route-constraint-reference for a more detailed explanation of route constraints
that are provided by the framework.
Additional overloads of MapRoute accept values for constraints , dataTokens , and defaults . These additional
parameters of MapRoute are defined as type object . The typical usage of these parameters is to pass an
anonymously typed object, where the property names of the anonymous type match route parameter names.
The following two examples create equivalent routes:
routes.MapRoute(
name: "default_route",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "default_route",
template: "{controller=Home}/{action=Index}/{id?}");
TIP
The inline syntax for defining constraints and defaults can be more convenient for simple routes. However, there are
features such as data tokens which are not supported by inline syntax.
routes.MapRoute(
name: "blog",
template: "Blog/{*article}",
defaults: new { controller = "Blog", action = "ReadArticle" });
This template will match a URL path like and will extract the values
/Blog/All-About-Routing/Introduction
{ controller = Blog, action = ReadArticle, article = All-About-Routing/Introduction } . The default route values
for controller and action are produced by the route even though there are no corresponding route
parameters in the template. Default values can be specified in the route template. The article route parameter
is defined as a catch-all by the appearance of an asterix * before the route parameter name. Catch-all route
parameters capture the remainder of the URL path, and can also match the empty string.
This example adds route constraints and data tokens:
routes.MapRoute(
name: "us_english_products",
template: "en-US/Products/{id}",
defaults: new { controller = "Products", action = "Details" },
constraints: new { id = new IntRouteConstraint() },
dataTokens: new { locale = "en-US" });
This template will match a URL path like /en-US/Products/5 and will extract the values
{ controller = Products, action = Details, id = 5 } and the data tokens { locale = en-US } .
URL generation
The Route class can also perform URL generation by combining a set of route values with its route template.
This is logically the reverse process of matching the URL path.
TIP
To better understand URL generation, imagine what URL you want to generate and then think about how a route
template would match that URL. What values would be produced? This is the rough equivalent of how URL generation
works in the Route class.
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
With the route values { controller = Products, action = List } , this route will generate the URL
/Products/List . The route values are substituted for the corresponding route parameters to form the URL path.
Since id is an optional route parameter, it's no problem that it doesn't have a value.
With the route values { controller = Home, action = Index } , this route will generate the URL / . The route
values that were provided match the default values so the segments corresponding to those values can be safely
omitted. Note that both URLs generated would round-trip with this route definition and produce the same route
values that were used to generate the URL.
TIP
An app using ASP.NET MVC should use UrlHelper to generate URLs instead of calling into routing directly.
For more details about the URL generation process, see url-generation-reference.
Routes must configured in the Configure method in the Startup class. The sample below uses these APIs:
RouteBuilder
Build
MapGet Matches only HTTP GET requests
UseRouter
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var trackPackageRouteHandler = new RouteHandler(context =>
{
var routeValues = context.GetRouteData().Values;
return context.Response.WriteAsync(
$"Hello! Route values: {string.Join(", ", routeValues)}");
});
routeBuilder.MapRoute(
"Track Package Route",
"package/{operation:regex(^track|create|detonate$)}/{id:int}");
The table below shows the responses with the given URIs.
URI RESPONSE
If you are configuring a single route, call app.UseRouter passing in an IRouter instance. You won't need to call
RouteBuilder .
The framework provides a set of extension methods for creating routes such as:
MapRoute
MapGet
MapPost
MapPut
MapDelete
MapVerb
Some of these methods such as MapGet require a RequestDelegate to be provided. The RequestDelegate will be
used as the route handler when the route matches. Other methods in this family allow configuring a middleware
pipeline which will be used as the route handler. If the Map method doesn't accept a handler, such as MapRoute ,
then it will use the DefaultHandler .
The Map[Verb] methods use constraints to limit the route to the HTTP Verb in the method name. For example,
see MapGet and MapVerb.
You can use the * character as a prefix to a route parameter to bind to the rest of the URI - this is called a catch-
all parameter. 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). Catch-all parameters can also match the empty
string.
Route 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 has a value only when one is provided.
Route parameters may also have constraints, which must match the route value bound from the URL. Adding a
colon : and constraint name after the route parameter name specifies an inline constraint on a route
parameter. If the constraint requires arguments those are provided enclosed in parentheses ( ) after the
constraint name. Multiple inline constraints can be specified by appending another colon : and constraint
name. The constraint name is passed to the IInlineConstraintResolver service to create an instance of
IRouteConstraint to use in URL processing. For example, the route template blog/{article:minlength(10)}
specifies the minlength constraint with the argument 10 . For more description route constraints, and a listing
of the constraints provided by the framework, see route-constraint-reference.
The following table demonstrates some route templates and their behavior.
ROUTE TEMPLATE EXAMPLE MATCHING URL NOTES
Using a template is generally the simplest approach to routing. Constraints and defaults can also be specified
outside the route template.
TIP
Enable Logging to see how the built in routing implementations, such as Route , match requests.
WARNING
Avoid using constraints for input 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 similar
routes, not to validate the inputs for a particular route.
The following table demonstrates some route constraints and their expected behavior.
WARNING
Route constraints that verify the URL can be converted to a CLR type (such as int or DateTime ) always use the
invariant culture - they assume the URL is non-localizable. The framework-provided route constraints do not modify the
values stored in route values. All route values parsed from the URL will be stored as strings. For example, the Float route
constraint will attempt to convert the route value to a float, but the converted value is used only to verify it can be
converted to a float.
TIP
Regular expressions use delimiters and tokens similar to those used by Routing and the C# language, and so those tokens
must be escaped. For example, to use the regular expression ^\d{3}-\d{2}-\d{4}$ in Routing, it needs to have the \
characters typed in as \\ in the C# source file to escape the \ string escape character (unless using verbatim string
literals). The { and } characters need to be escaped by doubling them to escape the Routing parameter delimiter
characters. The resulting regular expression is ^\\d{{3}}-\\d{{2}}-\\d{{4}}$ .
TIP
Regular expressions used in routing will often start with the ^ character (match starting position of the string) and end
with the $ character (match ending position of the string) to ensure that the regular expression must match the entire
route parameter value. Without the ^ and $ characters the regular expression will match any sub-string within the
string, which is often not desirable. For example, the regular expression [a-z]{2} will match the strings hello and
123abc456 because each contains a sequence of two lowercase characters somewhere in the string. However, the regular
expression ^[a-z]{2}$ will match neither hello or 123abc456 because it matches only exactly a sequence of two
lowercase characters, for example, MZ . Refer to .NET Framework Regular Expressions for more information on regular
expression syntax.
TIP
To constrain a parameter to a known set of possible values, you can use a regular expression ( for example
{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 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.
context.Response.ContentType = "text/html";
await context.Response.WriteAsync("Menu<hr/>");
await context.Response.WriteAsync($"<a href='{path}'>Create Package 123</a><br/>");
});
If a route has a default value that doesn't correspond to 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.
URL Rewriting Middleware in ASP.NET Core
3/14/2017 14 min to read Edit on GitHub
NOTE
URL rewriting can reduce the performance of an application. Where feasible, you should limit the number and complexity of
rules.
Package
To include the middleware in your project, add a reference to the Microsoft.AspNetCore.Rewrite package. The
middleware depends on .NET Framework 4.5.1 or .NET Standard 1.3 or later. This feature is available for apps that
target ASP.NET Core 1.1.0 or later.
app.UseRewriter(options);
URL redirect
Use AddRedirect() to redirect requests. The first parameter will contain your regex for matching on the path of the
incoming URL. The second parameter is the replacement string. The third parameter, if present, specifies the status
code. If you don't specify the status code, it defaults to 302 (Found), which indicates that the resource has been
temporarily moved or replaced.
app.UseRewriter(options);
In a browser with developer tools enabled, make a request to the sample application with the path
/redirect-rule/1234/5678 . The regex matches the request path on redirect-rule/(.*) , and the path is replaced
with /redirected/1234/5678 . The redirect URL is sent back to the client with a 302 (Found) status code. The
browser makes a new request at the redirect URL, which will appear in the browser's address bar. Since no rules in
the sample application match on the redirect URL, the second request receives a 200 (OK) response from the
application and the body of the response shows the redirect URL. A complete roundtrip is made to the server
when a URL is redirected.
Original Request: /redirect-rule/1234/5678
The part of the expression contained by parentheses is called a capture group. The dot ( . ) of the expression
means match any character, and the asterisk ( * ) signifies to match the preceding character zero or more times.
Therefore, the last two path segments of the URL, 1234/5678 , are captured by capture group (.*) . Any value you
provide in the request URL after redirect-rule/ will be captured by this single capture group.
In the replacement string, captured groups are injected into the string with the dollar sign ( $ ) followed by the
sequence number of the capture. The first capture group value is obtained with $1 , the second with $2 , and they
continue in sequence for the capture groups in your regex. There is only one captured group in the redirect rule
regex in the sample application, so there is only one injected group in the replacement string, which is $1 . When
the rule is applied, the URL becomes /redirected/1234/5678 .
URL redirect to a secure endpoint
Use AddRedirectToHttps() to redirect insecure requests to the same host and path with secure HTTPS protocol (
https:// ) with the flexibility to choose the status code and port. If the status code is not supplied, the middleware
will default to 302 (Found). If the port is not supplied, the middleware will default to null , which means the
protocol will change to https:// and the client will access the resource on port 443. The example shows how to
set the status code to 301 (Moved Permanently) and change the port to 5001.
app.UseRewriter(options);
Use AddRedirectToHttpsPermanent() to redirect insecure requests to the same host and path with secure HTTPS
protocol ( https:// on port 443). The middleware will set the status code to 301 (Moved Permanently).
The sample application is capable of demonstrating how to use AddRedirectToHttps() or
AddRedirectToHttpsPermanent() . Add the extension method to the RewriteOptions() . Make an insecure request to
the application at any URL. In order to see the response in a browser, you will probably need to dismiss a browser
security warning that the self-signed certificate is untrusted.
Original Request using AddRedirectToHttps(301, 5001) : /secure
app.UseRewriter(options);
The first thing you will notice in the regex is the carat ( ^ ) at the beginning of the expression. This means that
matching should be attempted starting at the beginning of the URL path.
In the earlier example with the redirect rule, redirect-rule/(.*) , there is no carat at the start of the regex;
therefore, any characters may precede redirect-rule/ in the path for a successful match.
PATH MATCH
/redirect-rule/1234/5678 Yes
/my-cool-redirect-rule/1234/5678 Yes
PATH MATCH
/anotherredirect-rule/1234/5678 Yes
The rewrite rule, ^rewrite-rule/(\d+)/(\d+) , will only match paths if they start with rewrite-rule/ . Notice the
difference in matching between the rewrite rule below and the redirect rule above.
PATH MATCH
/rewrite-rule/1234/5678 Yes
/my-cool-rewrite-rule/1234/5678 No
/anotherrewrite-rule/1234/5678 No
Following the ^rewrite-rule/ portion of the expression, there are two capture groups, (\d+)/(\d+) . The \d
signifies match a digit (number). The plus sign ( + ) means match one or more of the preceding character.
Therefore, the URL must contain a number followed by a forward-slash followed by another number. These
capture groups are injected into the resultant rewritten URL as $1 and $2 . The rewrite rule replacement string
places the captured groups into the querystring. The requested path of /rewrite-rule/1234/5678 is rewritten to
obtain the resource at /rewritten?var1=1234&var2=5678 . If a querystring is present on the original request, it's
preserved when the URL is rewritten.
There is no roundtrip to the server to obtain the resource. If the resource exists, it's fetched and returned to the
client with a 200 (OK) status code. Because the client isn't redirected, the URL in the browser address bar doesn't
change. As far as the client is concerned, the URL rewrite operation never occurred.
NOTE
skipRemainingRules: true should be used whenever possible, because matching rules is an expensive process and slows
down application response time. For the fastest application response, order your rewrite rules from most frequently matched
to least frequently matched and skip the processing of the remaining rules when a match occurs and no additional rule
processing is required.
Apache mod_rewrite
You can apply Apache mod_rewrite rules with AddApacheModRewrite() . The first parameter takes an IFileProvider ,
which is provided in the sample application via Dependency Injection by injecting the IHostingEnvironment and
using it to provide the ContentRootFileProvider . The second parameter is the path to your rules file, which is
ApacheModRewrite.txt in the sample application. You must make sure that the rules file is deployed with the
application. For more information and examples of mod_rewrite rules, see Apache mod_rewrite.
app.UseRewriter(options);
The sample application will redirect requests from /apache-mod-rules-redirect/(.\*) to /redirected?id=$1 . The
response status code is 302 (Found).
Su p p o r t e d se r v e r v a r i a b l e s
app.UseRewriter(options);
The sample application will rewrite requests from /iis-rules-rewrite/(.*) to /rewritten?id=$1 . The response is
sent to the client with a 200 (OK) status code.
<rewrite>
<rules>
<rule name="Rewrite segment to id querystring" stopProcessing="true">
<match url="^iis-rules-rewrite/(.*)$" />
<action type="Rewrite" url="rewritten?id={R:1}" appendQueryString="false"/>
</rule>
</rules>
</rewrite>
If you have an active IIS Rewrite Module with server-level rules configured that would impact your application in
undesirable ways, you can disable the IIS Rewrite Module for an application. For more information, see Disabling
IIS modules.
Unsupported features
The middleware does not support the following IIS URL Rewrite Module features:
Global rules (Basic Middleware #169)
Rewrite Maps (Basic Middleware #168)
CustomResponse action (Basic Middleware #135)
Custom Server Variables (Basic Middleware #183)
trackAllCaptures (Basic Middleware #178)
Wildcards
LogRewrittenUrl
Supported server variables
The middleware supports the following IIS URL Rewrite Module server variables:
CONTENT_LENGTH
CONTENT_TYPE
HTTP_ACCEPT
HTTP_CONNECTION
HTTP_COOKIE
HTTP_HOST
HTTP_REFERER
HTTP_URL
HTTP_USER_AGENT
HTTPS
LOCAL_ADDR
QUERY_STRING
REMOTE_ADDR
REMOTE_PORT
REQUEST_FILENAME
REQUEST_URI
NOTE
You can also obtain an IFileProvider via a PhysicalFileProvider . This approach may provide greater flexibility for the
location of your rewrite rules files. Make sure that your rewrite rules files are deployed to the server at the path you provide.
Method-based rule
Use Add(Action<RewriteContext> applyRule) to implement your own rule logic in a method. The RewriteContext
exposes the HttpContext for use in your method. The context.Result determines how additional pipeline
processing is handled.
CONTEXT.RESULT ACTION
RuleResult.SkipRemainingRules Stop applying rules and send the context to the next
middleware
var options = new RewriteOptions()
.AddRedirect("redirect-rule/(.*)", "redirected/$1")
.AddRewrite(@"^rewrite-rule/(\d+)/(\d+)", "rewritten?var1=$1&var2=$2", skipRemainingRules: true)
.AddApacheModRewrite(env.ContentRootFileProvider, "ApacheModRewrite.txt")
.AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml")
.Add(RedirectXMLRequests)
.Add(new RedirectImageRequests(".png", "/png-images"))
.Add(new RedirectImageRequests(".jpg", "/jpg-images"));
app.UseRewriter(options);
The sample application demonstrates a method that redirects requests for paths that end with .xml . If you make a
request for /file.xml , it's redirected to /xmlfiles/file.xml . The status code is set to 301 (Moved Permanently).
For a redirect, you must explicitly set the status code of the response; otherwise, a 200 (OK) status code will be
returned and the redirect won't occur on the client.
// Because we're redirecting back to the same app, stop processing if the request has already been
redirected
if (request.Path.StartsWithSegments(new PathString("/xmlfiles")))
{
return;
}
if (request.Path.Value.EndsWith(".xml", StringComparison.OrdinalIgnoreCase))
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = "/xmlfiles" + request.Path + request.QueryString;
}
}
app.UseRewriter(options);
The values of the parameters in the sample application for the extension and the newPath are checked to meet
several conditions. The extension must contain a value, and the value must be .png, .jpg, or .gif. If the newPath
isn't valid, an ArgumentException is thrown. If you make a request for image.png, it's redirected to
/png-images/image.png . If you make a request for image.jpg, it's redirected to /jpg-images/image.jpg . The status
code is set to 301 (Moved Permanently), and the context.Result is set to stop processing rules and send the
response.
public class RedirectImageRequests : IRule
{
private readonly string _extension;
private readonly PathString _newPath;
if (!Regex.IsMatch(extension, @"^\.(png|jpg|gif)$"))
{
throw new ArgumentException("The extension is not valid. The extension must be .png, .jpg, or
.gif.", nameof(extension));
}
if (!Regex.IsMatch(newPath, @"(/[A-Za-z0-9]+)+?"))
{
throw new ArgumentException("The path is not valid. Provide an alphanumeric path that starts with
a forward slash.", nameof(newPath));
}
_extension = extension;
_newPath = new PathString(newPath);
}
// Because we're redirecting back to the same app, stop processing if the request has already been
redirected
if (request.Path.StartsWithSegments(new PathString(_newPath)))
{
return;
}
if (request.Path.Value.EndsWith(_extension, StringComparison.OrdinalIgnoreCase))
{
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = _newPath + request.Path + request.QueryString;
}
}
}
Regex examples
REGEX STRING & REPLACEMENT STRING &
GOAL MATCH EXAMPLE OUTPUT EXAMPLE
Resources
Application Startup
Middleware
Regular expressions in .NET
Regular expression language - quick reference
Apache mod_rewrite
Using Url Rewrite Module 2.0 (for IIS)
URL Rewrite Module Configuration Reference
IIS URL Rewrite Module Forum
Keep a simple URL structure
10 URL Rewriting Tips and Tricks
To slash or not to slash
Introduction to Error Handling in ASP.NET Core
3/3/2017 4 min to read Edit on GitHub
Put UseDeveloperExceptionPage before any middleware you want to catch exceptions in, such as app.UseMvc .
WARNING
Enable the developer exception page only when the app is running in the Development environment. You don't want
to share detailed exception information publicly when the app runs in production. Learn more about configuring
environments.
To see the developer exception page, run the sample application with the environment set to Development , and
add ?throw=true to the base URL of the app. The page includes several tabs with information about the exception
and the request. The first tab includes a stack trace.
The next tab shows the query string parameters, if any.
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.
Configuring a custom exception handling page
It's a good idea to configure an exception handler page to use when the app is not running in the Development
environment.
In an MVC app, don't explicitly decorate the error handler action method with HTTP method attributes, such as
HttpGet . Using explicit verbs could prevent some requests from reaching the method.
[Route("/Error")]
public IActionResult Index()
{
// Handle error here
}
app.UseStatusCodePages();
By default, this middleware adds simple, text-only handlers for common status codes, such as 404:
The middleware supports several different extension methods. One takes a lambda expression, another takes a
content type and format string.
There are also redirect extension methods. One sends a 302 status code to the client, and one returns the original
status code to the client but also executes the handler for the redirect URL.
app.UseStatusCodePagesWithRedirects("/error/{0}");
app.UseStatusCodePagesWithReExecute("/error/{0}");
If you need to disable status code pages for certain requests, you can do so:
Exception-handling code
Code in exception handling pages can throw exceptions. It's often a good idea for production error pages to
consist of purely static content.
Also, be aware that once the headers for a response have been sent, you can't change the response's status code,
nor can any exception pages or handlers run. The response must be completed or the connection aborted.
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 sends a 500 Internal Server Error
response with no body. If it catches an exception after the headers have been sent, it closes 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.
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.
By Rick Anderson, Damien Bowden, Bart Calixto, Nadeem Afana, and Hisham Bin Ateya
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
support 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
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
namespace Localization.StarterWeb.Controllers
{
[Route("api/[controller]")]
public class AboutController : Controller
{
private readonly IStringLocalizer<AboutController> _localizer;
[HttpGet]
public string Get()
{
return _localizer["About Title"];
}
}
}
In the code above, the IStringLocalizer<T> implementation comes from Dependency Injection. 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.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
namespace Localization.StarterWeb.Controllers
{
public class BookController : Controller
{
private readonly IHtmlLocalizer<BookController> _localizer;
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;
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.
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:
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
implementation of IViewLocalizer :
@using Microsoft.AspNetCore.Mvc.Localization
@{
ViewData["Title"] = Localizer["About"];
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>
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:
KEY VALUE
The rendered view would contain the HTML markup from the resource file.
NOTE
You generally want to only localize text and not HTML.
@using Microsoft.AspNetCore.Mvc.Localization
@using Localization.StarterWeb.Services
@{
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
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; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
In ASP.NET Core MVC 1.1.0 and higher, non-validation attributes are localized. ASP.NET Core MVC 1.0 does not
look up localized strings for non-validation attributes.
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".
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.
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/Home/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.
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.
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 messages 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. Note, the localization middleware must be configured before any middleware
which might check the request culture (for example, app.UseMvc() ).
app.UseRequestLocalization(new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US"),
// Formatting numbers, dates, etc.
SupportedCultures = supportedCultures,
// UI strings that we have localized.
SupportedUICultures = supportedCultures
});
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
1. QueryStringRequestCultureProvider
2. CookieRequestCultureProvider
3. AcceptLanguageHeaderRequestCultureProvider
The default list goes from most specific to least specific. Later in the article we'll see how you can change the order
and even add a custom culture provider. If none of the providers can determine the request culture, 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. By default,
the QueryStringRequestCultureProvider is registered as the first localization provider in the
RequestCultureProvider list. 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 ASP.NET Core culture cookie. Use the
MakeCookieValue method to create a cookie.
The CookieRequestCultureProvider DefaultCookieName returns the default cookie name used to track the users
preferred culture information. The default cookie name is ".AspNetCore.Culture".
The cookie format is c=%LANGCODE%|uic=%LANGCODE% , where c is Culture and uic is UICulture , for example:
c='en-UK'|uic='en-US'
If you only specify one of culture info and UI culture, the specified culture will be used for both culture info and UI
culture.
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.
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("fr")
};
@using Microsoft.AspNetCore.Builder
@using Microsoft.AspNetCore.Http.Features
@using Microsoft.AspNetCore.Localization
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.Extensions.Options
@{
var requestCulture = Context.Features.Get<IRequestCultureFeature>();
var cultureItems = LocOptions.Value.SupportedUICultures
.Select(c => new SelectListItem { Value = c.Name, Text = c.DisplayName })
.ToList();
}
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>© 2015 - Localization.StarterWeb</p>
</div>
<div class="col-md-6 text-right">
@await Html.PartialAsync("_SelectLanguagePartial")
</div>
</div>
</footer>
</div>
[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 plug in the _SelectLanguagePartial.cshtml to sample code for this project. The Localization.StarterWeb
project on GitHub has code to flow the RequestLocalizationOptions to a Razor partial through the Dependency
Injection container.
Additional Resources
Localization.StarterWeb project used in the article.
Resource Files in Visual Studio
Resources in .resx Files
3/17/2017 15 min to read Edit on GitHub
Simple configuration
The following console app uses the JSON configuration provider:
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
Configuration = builder.Build();
Console.WriteLine($"option1 = {Configuration["option1"]}");
Console.WriteLine($"option2 = {Configuration["option2"]}");
Console.WriteLine(
$"option1 = {Configuration["subsection:suboption1"]}");
}
}
The app reads and displays the following configuration settings:
{
"option1": "value1_from_json",
"option2": 2,
"subsection": {
"suboption1": "subvalue1_from_json"
}
}
Configuration consists of a hierarchical list of name-value pairs in which the nodes are separated by a colon. To
retrieve a value, you access the Configuration indexer with the corresponding items key:
Console.WriteLine($"option1 = {Configuration["subsection:suboption1"]}");
Name/value pairs written to the built in Configuration providers are not persisted, however, you can create a
custom provider that saves values. See custom configuration provider.
The sample above uses the configuration indexer to read values. When the Configuration object is available,
the indexer is a convenient way to access setting. To flow information from configuration into other parts of the
app outside of Startup , we recommend using the options pattern. We'll show that later in this document.
It's typical to have different configuration settings for different environments, for example, development, test
and production. The following highlighted code hooks up two configuration providers to three sources:
1. JSON provider, reading appsettings.json
2. JSON provider, reading appsettings.<EnvironmentName>.json
3. Environment variables provider
See AddJsonFile for an explanation of the parameters. reloadOnChange is only supported in ASP.NET Core 1.1
and higher.
Configuration sources are read in the order they are specified. In the code above, the environment variables are
read last. Any configuration values set through the environment would replace those set in the two previous
providers.
The environment is typically set to one of Development , Staging , or Production . See Working with Multiple
Environments for more information.
Configuration considerations:
IOptionsSnapshot can reload configuration data when it changes. Use IOptionsSnapshot if you need to
reload configuration data. See IOptionsSnapshot for more information.
Configuration keys are case insensitive.
A best practice is to specify environment variables last, so that the local environment can override anything
set in deployed configuration files.
Never store passwords or other sensitive data in configuration provider code or in plain text configuration
files. You also shouldn't use production secrets in your development or test environments. Instead, specify
secrets outside the project tree, so they cannot be accidentally committed into your repository. Learn more
about Working with Multiple Environments and managing Safe storage of app secrets during development.
If : cannot be used in environment variables in your system, replace : with __ (double underscore).
In the following code, the JSON configuration provider is enabled. The MyOptions class is added to the service
container and bound to configuration.
Configuration = builder.Build();
}
{
"option1": "value1_from_json",
"option2": 2
}
In the following code, a second IConfigureOptions<TOptions> service is added to the service container. It uses a
delegate to configure the binding with MyOptions .
You can add multiple configuration providers. Configuration providers are available in NuGet packages. They
are applied in order they are registered.
Each call to Configure<TOptions> adds an IConfigureOptions<TOptions> service to the service container. In the
example above, the values of Option1 and Option2 are both specified in appsettings.json, but the value of
Option1 is overridden by the configured delegate in the highlighted code above.
When more than one configuration service is enabled, the last configuration source specified wins. With the
code above, the HomeController.Index method returns option1 = value1_from_action, option2 = 2 .
When you bind options to configuration, each property in your options type is bound to a configuration key of
the form property[:sub-property:] . For example, the MyOptions.Option1 property is bound to the key Option1 ,
which is read from the option1 property in appsettings.json. A sub-property sample is shown later in this
article.
In the following code, a third IConfigureOptions<TOptions> service is added to the service container. It binds
MySubOptions to the section subsection of the appsettings.json file:
{
"option1": "value1_from_json",
"option2": -1,
"subsection": {
"suboption1": "subvalue1_from_json",
"suboption2": 200
}
}
IOptionsSnapshot
Requires ASP.NET Core 1.1 or higher.
IOptionsSnapshot supports reloading configuration data when the configuration file has changed. It also has
minimal overhead if you don't care about changes. Using IOptionsSnapshot with reloadOnChange: true , the
options are bound to IConfiguration and reloaded when changed.
The following sample demonstrates how a new IOptionsSnapshot is created after config.json changes. Requests
to server will return the same time when config.json has not changed. The first request after config.json
changes will show a new time.
Refreshing the browser doesn't change the message value or time displayed (when config.json has not
changed).
Change and save the config.json and then refresh the browser:
In-memory provider and binding to a POCO class
The following sample shows how to use the in-memory provider and bind to a class:
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
Configuration values are returned as strings, but binding enables the construction of objects. Binding allows
you to retrieve POCO objects or even entire object graphs. The following sample shows how to bind to
MyWindow and use the options pattern with a ASP.NET Core MVC app:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
GetValue
The following sample demonstrates the GetValue<T> extension method:
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
The ConfigurationBinders GetValue<T> method allows you to specify a default value (80 in the sample).
GetValue<T> is for simple scenarios and does not bind to entire sections. GetValue<T> gets scalar values from
GetSection(key).Value converted to a specific type.
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
Console.WriteLine($"Height {appConfig.Window.Height}");
}
}
ASP.NET Core 1.1 and higher can use Get<T> , which works with entire sections. Get<T> can be more
convienent than using Bind . The following code shows how to use Get<T> with the sample above:
[Fact]
public void CanBindObjectTree()
{
var dict = new Dictionary<string, string>
{
{"App:Profile:Machine", "Rick"},
{"App:Connection:Value", "connectionstring"},
{"App:Window:Height", "11"},
{"App:Window:Width", "11"}
};
var builder = new ConfigurationBuilder();
builder.AddInMemoryCollection(dict);
var config = builder.Build();
Assert.Equal("Rick", options.Profile.Machine);
Assert.Equal(11, options.Window.Height);
Assert.Equal(11, options.Window.Width);
Assert.Equal("connectionstring", options.Connection.Value);
}
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CustomConfigurationProvider
{
public class EFConfigSource : IConfigurationSource
{
private readonly Action<DbContextOptionsBuilder> _optionsAction;
Create the custom configuration provider by inheriting from ConfigurationProvider. The configuration provider
initializes the database when it's empty:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CustomConfigurationProvider
{
public class EFConfigProvider : ConfigurationProvider
{
public EFConfigProvider(Action<DbContextOptionsBuilder> optionsAction)
{
OptionsAction = optionsAction;
}
The highlighted values from the database ("value_from_ef_1" and "value_from_ef_2") are displayed when the
sample is run.
You can add an EFConfigSource extension method for adding the configuration source:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace CustomConfigurationProvider
{
public static class EntityFrameworkExtensions
{
public static IConfigurationBuilder AddEntityFrameworkConfig(
this IConfigurationBuilder builder, Action<DbContextOptionsBuilder> setup)
{
return builder.Add(new EFConfigSource(setup));
}
}
}
using System;
using System.IO;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using CustomConfigurationProvider;
Console.WriteLine("key1={0}", config["key1"]);
Console.WriteLine("key2={0}", config["key2"]);
Console.WriteLine("key3={0}", config["key3"]);
}
}
Note the sample adds the custom EFConfigProvider after the JSON provider, so any settings from the database
will override settings from the appsettings.json file.
Using the following appsettings.json file:
{
"ConnectionStrings": {
"DefaultConnection": "Server=
(localdb)\\mssqllocaldb;Database=CustomConfigurationProvider;Trusted_Connection=True;MultipleActiveResultSe
ts=true"
},
"key1": "value_from_json_1",
"key2": "value_from_json_2",
"key3": "value_from_json_3"
}
key1=value_from_ef_1
key2=value_from_ef_2
key3=value_from_json_3
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
Which displays:
Hello Bob
Left 1234
The GetSwitchMappings method allows you to use - rather than / and it strips the leading subkey prefixes.
For example:
Displays:
Hello Bob
Left 7734
Command-line arguments must include a value (it can be null). For example:
Is OK, but
results in an exception. An exception will be thrown if you specify a command-line switch prefix of - or -- for
which theres no corresponding switch mapping.
Additional Resources
Working with Multiple Environments
Safe storage of app secrets during development
Dependency Injection
Azure Key Vault configuration provider
Introduction to Logging in ASP.NET Core
3/3/2017 16 min to read Edit on GitHub
ASP.NET Core dependency injection (DI) provides the ILoggerFactory instance. The AddConsole and AddDebug
extension methods are defined in the Microsoft.Extensions.Logging.Console and
Microsoft.Extensions.Logging.Debug packages. Each extension method calls the ILoggerFactory.AddProvider
method, passing in an instance of the provider.
NOTE
The sample application for this article adds logging providers in the Configure method of the Startup class. If you
want to get log output from code that executes earlier, add logging providers in the Startup class constructor instead.
You'll find information about each built-in logging provider and links to third-party logging providers later in the
article.
This example requests ILogger<TodoController> from DI to specify the TodoController class as the category of
logs that are created with the logger. Categories are explained later in this article.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/todo/invalidid
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (invalidid)
- ModelState is Valid
info: TodoApi.Controllers.TodoController[1002]
Getting item invalidid
warn: TodoApi.Controllers.TodoController[4000]
GetById(invalidid) NOT FOUND
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action TodoApi.Controllers.TodoController.GetById (TodoApi) in 243.2636ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 628.9188ms 404
````
Here's an example of what you see in the Debug window if you run the sample application from Visual Studio in
debug mode and go to URL `http://localhost:55070/api/todo/0`:
From these examples you can see that ASP.NET Core itself and your application code are using the same logging
API and the same logging providers.
The remainder of this article explains some details and options for logging.
## NuGet packages
## Log category
A *category* is specified with each log that you create. The category may be any string, but a convention is
to use the fully qualified name of the class from which the logs are written. For example:
"TodoApi.Controllers.TodoController".
You specify the category when you create a logger object or request one from DI, and the category is
automatically included with every log written by that logger. You can specify the category explicitly or you
can use an extension method that derives the category from the type. To specify the category explicitly, call
`CreateLogger` on an *ILoggerFactory* instance, as shown below.
[!code-csharp[](logging/sample/src/TodoApi/Controllers/TodoController.cs?
name=snippet_CreateLogger&highlight=7,10)]
Most of the time it will be easier to use `ILogger<T>`, as in the following example.
[!code-csharp[](logging/sample/src/TodoApi/Controllers/TodoController.cs?
name=snippet_LoggerDI&highlight=7,10)]
This is equivalent to calling `CreateLogger` with the fully qualified type name of `T`.
## Log level
In the following code example, the names of the methods specify the log level:
[!code-csharp[](logging/sample/src/TodoApi/Controllers/TodoController.cs?
name=snippet_CallLogMethods&highlight=3,7)]
Log methods that include the level in the method name are [extension methods for ILogger]
(https://docs.microsoft.com/aspnet/core/api/microsoft.extensions.logging.loggerextensions) that the
*Microsoft.Extensions.Logging* package provides. Behind the scenes these methods call a `Log` method that
takes a `LogLevel` parameter. You can call the `Log` method directly rather than one of these extension
methods, but the syntax is relatively complicated. For more information, see the [ILogger interface]
(https://docs.microsoft.com/aspnet/core/api/microsoft.extensions.logging.ilogger) and the [logger extensions
source code]
(https://github.com/aspnet/Logging/blob/master/src/Microsoft.Extensions.Logging.Abstractions/LoggerExtensions
.cs).
* Trace = 0
* Trace = 0
For information that is valuable only to a developer debugging an issue. These messages 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"}`
* Debug = 1
For information that has short-term usefulness during development and debugging. Example: `Entering method
Configure with flag set to true.`
* Information = 2
For tracking the general flow of the application. These logs typically have some long-term value. Example:
`Request received for path /api/todo`
* Warning = 3
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 investigated. Handled exceptions are a
common place to use the `Warning` log level. Example: `FileNotFoundException for file quotes.txt.`
* Error = 4
For errors and exceptions that cannot be handled. These messages indicate a failure in the current activity
or operation (such as the current HTTP request), not an application-wide failure. Example log message:
`Cannot insert record due to duplicate key violation.`
* Critical = 5
For failures that require immediate attention. Examples: data loss scenarios, out of disk space.
You can use the log level to control how much log output is written to a particular storage medium or display
window. For example, in production you might want all logs of `Information` level and higher to go to a high-
volume data store, and all logs of `Warning` level and higher to go to a high-value data store. During
development you might normally direct only logs of `Warning` or higher severity to the console, but add
`Debug` level when you need to investigate a problem. The [Log filtering](#log-filtering) section later in
this article explains how to control which log levels a provider handles.
The ASP.NET Core framework writes `Debug` logs for framework events. Here's an example of what you see from
the console provider if you run the sample application with the minimum log level set to `Debug` and go to
URL `http://localhost:5000/api/todo/0`:
```console
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Request starting HTTP/1.1 GET http://localhost:5000/api/todo/0
dbug: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[4]
The request path /api/todo/0 does not match a supported file type
dbug: Microsoft.AspNetCore.Routing.Tree.TreeRouter[1]
Request successfully matched the route with name 'GetTodo' and template 'api/Todo/{id}'.
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[2]
Action 'TodoApi.Controllers.TodoController.Update (TodoApi)' with id '6cada879-f7a8-4152-b244-
7b41831791cc' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'
dbug: Microsoft.AspNetCore.Mvc.Internal.ActionSelector[2]
Action 'TodoApi.Controllers.TodoController.Delete (TodoApi)' with id '529c0e82-aea6-466c-bbe2-
e77ded858853' did not match the constraint 'Microsoft.AspNetCore.Mvc.Internal.HttpMethodActionConstraint'
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action TodoApi.Controllers.TodoController.GetById (TodoApi)
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
Executing action method TodoApi.Controllers.TodoController.GetById (TodoApi) with arguments (0) -
ModelState is Valid
info: TodoApi.Controllers.TodoController[1002]
Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
GetById(0) NOT FOUND
dbug: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action method TodoApi.Controllers.TodoController.GetById (TodoApi), returned result
Microsoft.AspNetCore.Mvc.NotFoundResult.
info: Microsoft.AspNetCore.Mvc.StatusCodeResult[1]
Executing HttpStatusCodeResult, setting HTTP status code 404
Executing HttpStatusCodeResult, setting HTTP status code 404
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
Executed action TodoApi.Controllers.TodoController.GetById (TodoApi) in 198.8402ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Request finished in 550.6837ms 404
dbug: Microsoft.AspNetCore.Server.Kestrel[9]
Connection id "0HKV8M5ARIH5P" completed keep alive response.
Log event ID
Each time you write a log, you can specify an event ID. The sample app does this by using a locally-defined
LoggingEvents class:
An event ID is an integer value that you can use to associate a set of logged events with one another. For
instance, a log for adding an item to a shopping cart could be event ID 1000 and a log for completing a purchase
could be event ID 1001.
In logging output, the event ID may be stored in a field or included in the text message, depending on the
provider. The Debug provider doesn't show event IDs, but the console provider shows them in brackets after the
category:
info: TodoApi.Controllers.TodoController[1002]
Getting item invalidid
warn: TodoApi.Controllers.TodoController[4000]
GetById(invalidid) NOT FOUND
The order of placeholders, not their names, determines which parameters are used for them. For example, if you
have the following code:
string p1 = "parm1";
string p2 = "parm2";
_logger.LogInformation("Parameter values: {p2}, {p1}", p1, p2);
The logging framework does message formatting in this way to make it possible for logging providers to
implement semantic logging, also known as structured logging. Because the arguments themselves are passed to
the logging system, not just the formatted message string, logging providers can store the parameter values as
fields in addition to the message string. For example, if you are directing your log output to Azure Table Storage,
and your logger method call looks like this:
Each Azure Table entity could have ID and RequestTime properties, which would simplify queries on log data.
You could find all logs within a particular RequestTime range, without having to parse the time out of the text
message.
Logging exceptions
The logger methods have overloads that let you pass in an exception, as in the following example:
Different providers handle the exception information in different ways. Here's an example of Debug provider
output from the code shown above.
The AddEventLog method has an overload that takes an EventLogSettings instance, which may contain a filtering
function in its Filter property. The TraceSource provider does not provide any of those overloads, since its
logging level and other parameters are based on the SourceSwitch and TraceListener it uses.
You can set filtering rules for all providers that are registered with an ILoggerFactory instance by using the
WithFilter extension method. The example below limits framework logs (category begins with "Microsoft" or
"System") to warnings while letting the app log at debug level.
If you want to use filtering to prevent all logs from being written for a particular category, you can specify
LogLevel.None as the minimum log level for that category. The integer value of LogLevel.None is 6, which is
higher than LogLevel.Critical (5).
The WithFilter extension method is provided by the Microsoft.Extensions.Logging.Filter NuGet package. The
method returns a new ILoggerFactory instance that will filter the log messages passed to all logger providers
registered with it. It does not affect any other ILoggerFactory instances, including the original ILoggerFactory
instance.
Log scopes
You can group a set of logical operations within a scope in order to attach the same data to each log that is
created as part of that set. For example, you might want every log created as part of processing a transaction to
include the transaction ID.
A scope is an IDisposable type that is returned by the ILogger.BeginScope<TState> method and lasts until it is
disposed. You use a scope by wrapping your logger calls in a using block, as shown here:
public IActionResult GetById(string id)
{
TodoItem item;
using (_logger.BeginScope("Message attached to logs created in the using block"))
{
_logger.LogInformation(LoggingEvents.GET_ITEM, "Getting item {ID}", id);
item = _todoRepository.Find(id);
if (item == null)
{
_logger.LogWarning(LoggingEvents.GET_ITEM_NOTFOUND, "GetById({ID}) NOT FOUND", id);
return NotFound();
}
}
return new ObjectResult(item);
}
info: TodoApi.Controllers.TodoController[1002]
=> RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById
(TodoApi) => Message attached to logs created in the using block
Getting item 0
warn: TodoApi.Controllers.TodoController[4000]
=> RequestId:0HKV9C49II9CK RequestPath:/api/todo/0 => TodoApi.Controllers.TodoController.GetById
(TodoApi) => Message attached to logs created in the using block
GetById(0) NOT FOUND
loggerFactory.AddConsole()
AddConsole overloads let you pass in an a minimum log level, a filter function, and a boolean that indicates
whether scopes are supported. Another option is to pass in an IConfiguration object, which can specify scopes
support and logging levels.
If you are considering the console provider for use in production, be aware that it has a significant impact on
performance.
When you create a new project in Visual Studio, the AddConsole method looks like this:
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
The settings shown limit framework logs to warnings while allowing the app to log at debug level, as explained in
the Log filtering section. For more information, see Configuration.
The Debug provider
The Microsoft.Extensions.Logging.Debug provider package writes log output by using the
System.Diagnostics.Debug class.
loggerFactory.AddDebug()
AddDebug overloads let you pass in a minimum log level or a filter function.
The EventSource provider
For apps that target ASP.NET Core 1.1.0 or higher, the Microsoft.Extensions.Logging.EventSource provider
package can implement event tracing. On Windows, it uses ETW. The provider is cross-platform, but there are no
event collection and display tools yet for Linux or macOS.
loggerFactory.AddEventSourceLogger()
The best way to collect and view logs is to use the PerfView utility. There are other tools for viewing ETW logs, but
PerfView provides the best experience for working with the ETW events emitted by ASP.NET.
To configure PerfView for collecting events logged by this provider, add the string
*Microsoft-Extensions-Logging to the Additional Providers list. (Don't miss the asterisk at the start of the
string.)
Capturing events on Nano Server requires some additional setup:
Connect PowerShell remoting to the Nano Server:
Enter-PSSession [name]
Add ETW providers for CLR, ASP.NET Core, and others as needed. The ASP.NET Core provider GUID is
3ac73b97-af73-50e9-0822-5da4367920d0 .
Run the site and do whatever actions you want tracing information for.
Stop the tracing session when you're finished:
Remove-EtwTraceSession MyAppTrace
The resulting C:\trace.etl file can be analyzed with PerfView as on other editions of Windows.
The Windows EventLog provider
The Microsoft.Extensions.Logging.EventLog provider package sends log output to the Windows Event Log.
loggerFactory.AddEventLog()
loggerFactory.AddTraceSource(sourceSwitchName);
AddTraceSource overloads let you pass in a source switch and a trace listener.
To use this provider, an application has to run on the .NET Framework (rather than .NET Core). The provider lets
you route messages to a variety of listeners, such as the TextWriterTraceListener used in the sample application.
The following example configures a TraceSource provider that logs Warning and higher messages to the console
window.
loggerFactory.AddAzureWebAppDiagnostics();
When you deploy to an App Service app, your application honors the settings in the Diagnostic Logs section of
the App Service blade of the Azure portal. When you change those settings, the changes take effect immediately
without requiring that you restart the app or redeploy code to it.
The default location for log files is in the D:\home\LogFiles\Application folder, and the default file name is
diagnostics-yyyymmdd.txt. The default file size limit is 10 MB and the default maximum number of files retained
is 2. The default blob name is {app-name}{timestamp}/yyyy/mm/dd/hh/{guid}-applicationLog.txt. For more
information about default behavior, see AzureAppServicesDiagnosticsSettings.
The provider only works when your project runs in the Azure environment. It has no effect when you run locally -
- it does not write to local files or local development storage for blobs.
NOTE
If you don't need to change the provider default settings, there's an alternative way to set up App Service logging in your
application. Install Microsoft.AspNetCore.AzureAppServicesIntegration (which includes the logging package as a
dependency), and call its extension method on WebHostBuilder in your Main method.
Behind the scenes, UseAzureAppServices calls UseIISIntegration and the logging provider extension method
AddAzureWebAppDiagnostics .
By Steve Smith
ASP.NET Core abstracts file system access through the use of File Providers.
View or download sample code
You can iterate through its directory contents or get a specific file's information by providing a subpath.
To request a provider from a controller, specify it in the controller's constructor and assign it to a local field. Use the
local instance from your action methods:
public class HomeController : Controller
{
private readonly IFileProvider _fileProvider;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace FileProviderSample
{
public class Startup
{
private IHostingEnvironment _hostingEnvironment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
_hostingEnvironment = env;
}
// 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.AddMvc();
<h2>Folder Contents</h2>
<ul>
@foreach (IFileInfo item in Model)
{
if (item.IsDirectory)
{
<li><strong>@item.Name</strong></li>
}
else
{
<li>@item.Name - @item.Length bytes</li>
}
}
</ul>
The result:
EmbeddedFileProvider
The EmbeddedFileProvider is used to access files embedded in assemblies. In .NET Core, you embed files in an
assembly with the <EmbeddedResource> element in the .csproj file:
<ItemGroup>
<EmbeddedResource Include="Resource.txt;**\*.js"
Exclude="bin\**;obj\**;**\*.xproj;packages\**;@(EmbeddedResource)" />
<Content Update="wwwroot\**\*;Views\**\*;Areas\**\Views;appsettings.json;web.config">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</Content>
</ItemGroup>
You can use globbing patterns when specifying files to embed in the assembly. These patterns can be used to
match one or more files.
NOTE
It's unlikely you would ever want to actually embed every .js file in your project in its assembly; the above sample is for demo
purposes only.
When creating an EmbeddedFileProvider , pass the assembly it will read to its constructor.
The snippet above demonstrates how to create an EmbeddedFileProvider with access to the currently executing
assembly.
Updating the sample app to use an EmbeddedFileProvider results in the following output:
NOTE
Embedded resources do not expose directories. Rather, the path to the resource (via its namespace) is embedded in its
filename using . separators.
TIP
The EmbeddedFileProvider constructor accepts an optional baseNamespace parameter. Specifying this will scope calls to
GetDirectoryContents to those resources under the provided namespace.
CompositeFileProvider
The CompositeFileProvider combines IFileProvider instances, exposing a single interface for working with files
from multiple providers. When creating the CompositeFileProvider , you pass one or more IFileProvider instances
to its constructor:
Updating the sample app to use a CompositeFileProvider that includes both the physical and embedded providers
configured previously, results in the following output:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Primitives;
namespace WatchConsole
{
public class Program
{
private static PhysicalFileProvider _fileProvider =
new PhysicalFileProvider(Directory.GetCurrentDirectory());
public static void Main(string[] args)
{
Console.WriteLine("Monitoring quotes.txt for changes (ctrl-c to quit)...");
while (true)
{
MainAsync().GetAwaiter().GetResult();
}
}
NOTE
Some file systems, such as Docker containers and network shares, may not reliably send change notifications. Set the
DOTNET_USE_POLLINGFILEWATCHER environment variable to 1 or true to poll the file system for changes every 4 seconds.
Globbing patterns
File system paths use wildcard patterns called globbing patterns. These simple patterns can be used to specify
groups of files. The two wildcard characters are * and ** .
*
Matches anything at the current folder level, or any filename, or any file extension. Matches are terminated by /
and . characters in the file path.
**
Matches anything across multiple directory levels. Can be used to recursively match many files within a directory
hierarchy.
Globbing pattern examples
directory/file.txt
Matches all bower.json files in directories exactly one level below the directory directory.
directory/**/*.txt
Matches all files with .txt extension found anywhere under the directory directory.
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.
A suitable constructor for type 'YourType' could not be located. Ensure the type is concrete and services
are registered for all parameters of a public constructor.
Constructor injection requires that only one applicable constructor exist. Constructor overloads are
supported, but only one overload can exist whose arguments can all be fulfilled by dependency injection. If
more than one exists, your app will throw an InvalidOperationException :
Multiple constructors accepting all given argument types have been found in type 'YourType'. There
should only be one applicable constructor.
Constructors can accept arguments that are not provided by dependency injection, but these must support
default values. For example:
Microsoft.AspNetCore.Hosting.IHostingEnvironment Singleton
Microsoft.Extensions.Logging.ILoggerFactory Singleton
Microsoft.Extensions.Logging.ILogger<T> Singleton
Microsoft.AspNetCore.Hosting.Builder.IApplicationBuilderF Transient
actory
SERVICE TYPE LIFETIME
Microsoft.AspNetCore.Http.IHttpContextFactory Transient
Microsoft.Extensions.Options.IOptions<T> Singleton
System.Diagnostics.DiagnosticSource Singleton
System.Diagnostics.DiagnosticListener Singleton
Microsoft.AspNetCore.Hosting.IStartupFilter Transient
Microsoft.Extensions.ObjectPool.ObjectPoolProvider Singleton
Microsoft.Extensions.Options.IConfigureOptions<T> Transient
Microsoft.AspNetCore.Hosting.Server.IServer Singleton
Microsoft.AspNetCore.Hosting.IStartup Singleton
Microsoft.AspNetCore.Hosting.IApplicationLifetime Singleton
Below is an example of how to add additional services to the container using a number of extension
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();
The features and middleware provided by ASP.NET, such as MVC, follow a convention of using a single
AddServiceName 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.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
NOTE
Each services.Add<ServiceName> extension method adds (and potentially configures) services. For example,
services.AddMvc() adds the services MVC requires. It's recommended that you follow this convention, placing
extension methods in the Microsoft.Extensions.DependencyInjection namespace, to encapsulate groups of
service registrations.
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
application uses Entity Framework Core and the ApplicationDbContext class for its persistence, none of that
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.
// GET: /characters/
public IActionResult Index()
{
PopulateCharactersIfNoneExist();
var characters = _characterRepository.ListAll();
return View(characters);
}
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
{
public class CharacterRepository : ICharacterRepository
{
private readonly ApplicationDbContext _dbContext;
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.
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 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.
Services that have dependencies should register them in the container. If a service's constructor requires a
primitive, such as a string , this can be injected by using the options pattern and configuration.
using System;
namespace DependencyInjectionSample.Interfaces
{
public interface IOperation
{
Guid OperationId { get; }
}
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:
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>();
}
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 (its Guid will be all zeroes). 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 getting 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; }
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 values.
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;
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 specify 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.
// Add Autofac
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterModule<DefaultModule>();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return new AutofacServiceProvider(container);
}
NOTE
When using a third-party DI container, you must change ConfigureServices so that it returns
IServiceProvider instead of void .
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 examples 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)
Working with multiple environments
3/15/2017 7 min to read Edit on GitHub
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.
View or download sample code
NOTE
On Windows and macOS, the specified environment name is case insensitive. Whether you set the variable to
Development or development or DEVELOPMENT the results will be the same. However, Linux is a case sensitive OS by
default. Environment variables, file names and settings should assume case sensitivity for best practice.
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 in Servers). For example, after adding another profile configured to use IIS Express, but using an
ASPNETCORE_ENVIRONMENT value of Staging , the launchSettings.json file in our sample project is shown below:
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:40088/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express (Staging)": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Staging"
}
}
}
}
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).
You can create multiple different launch profiles for various different configurations of your application,
including those that require other environment variables.
WARNING
Environment variables stored in launchSettings.json are not secured in any way and will be part of the source code
repository for your project, if you use one. Never store credentials or other secret data in this file. If you need a place
to store such data, use the Secret Manager tool described in Safe storage of app secrets during development.
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)
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
set ASPNETCORE_ENVIRONMENT="Development"
PowerShell
$Env:ASPNETCORE_ENVIRONMENT = "Development"
These commands take effect only for the current window. When the window is closed, the
ASPNETCORE_ENVIRONMENT setting reverts to the default setting or machine value. In order to set the value
globally on Windows open the Control Panel > System > Advanced system settings and add or edit the
ASPNETCORE_ENVIRONMENT value.
macOS
Setting the current environment for macOS can be done in-line when running the application;
export ASPNETCORE_ENVIRONMENT=Development
Machine level environment variables are set in the .bashrc or .bash_profile file. Edit the file using any text editor
and add the following statment.
export ASPNETCORE_ENVIRONMENT=Development
Linux
For Linux distros, use the export command at the command line for session based variable settings and
bash_profile file for machine level environment settings.
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.
NOTE
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 your Configure method to setup environment specific error
handling:
If the app is running in a Development environment, then it enables the runtime support necessary to use the
"BrowserLink" feature in Visual Studio, development-specific error pages (which typically should not be run in
production) and special database error pages (which provide a way to apply migrations and should therefore
only be used in development). 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.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-
value="absolute" />
<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 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 ASPNETCORE_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.
NOTE
Calling WebHostBuilder.UseStartup<TStartup>() overrides configuration sections.
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, of the
form Configure{EnvironmentName}() and Configure{EnvironmentName}Services() . If you define a method
ConfigureDevelopment() it will be called instead of Configure() when the environment 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
applications 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
Introduction to hosting in ASP.NET Core
3/7/2017 7 min to read Edit on GitHub
By Steve Smith
To run an ASP.NET Core app, you need to configure and launch a host using WebHostBuilder .
What is a Host?
ASP.NET Core apps require a host in which to execute. A host must implement the IWebHost interface, which
exposes collections of features and services, and a Start method. The host is typically created using an instance
of a WebHostBuilder , which builds and returns a WebHost instance. The WebHost references the server that will
handle requests. Learn more about servers.
What is the difference between a host and a server?
The host is responsible for application startup and lifetime management. The server is responsible for accepting
HTTP requests. Part of the host's responsibility includes ensuring the application's services and the server are
available and properly configured. You can think of the host as being a wrapper around the server. The host is
configured to use a particular server; the server is unaware of its host.
Setting up a Host
You create a host using an instance of WebHostBuilder . This is typically done in your app's entry point:
public static void Main , (which in the project templates is located in a Program.cs file). A typical Program.cs,
shown below, demonstrates how to use a WebHostBuilder to build a host.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
The WebHostBuilder is responsible for creating the host that will bootstrap the server for the app. WebHostBuilder
requires you provide a server that implements IServer ( UseKestrel in the code above). UseKestrel specifies the
Kestrel server will be used by the app.
The server's content root determines where it searches for content files, like MVC View files. The default content
root is the folder from which the application is run.
NOTE
Specifying Directory.GetCurrentDirectory as the content root will use the web project's root folder as the app's content
root when the app is started from this folder (for example, calling dotnet run from the web project folder). This is the
default used in Visual Studio and dotnet new templates.
If the app should work with IIS, the UseIISIntegration method should be called as part of building the host. Note
that this does not configure a server, like UseKestrel does. To use IIS with ASP.NET Core, you must specify both
UseKestrel and UseIISIntegration . Kestrel is designed to be run behind a proxy and should not be deployed
directly facing the Internet. UseIISIntegration specifies IIS as the reverse proxy server.
NOTE
UseKestrel and UseIISIntegration are very different actions. IIS is only used as a reverse proxy. UseKestrel creates
the web server and hosts the code. UseIISIntegration specifies IIS as the reverse proxy server. It also examines
environment variables used by IIS/IISExpress and makes decisions like which dynamic port use, which headers to set, etc.
However, it doesn't deal with or create an IServer .
A minimal implementation of configuring a host (and an ASP.NET Core app) would include just a server and
configuration of the app's request pipeline:
host.Run();
NOTE
When setting up a host, you can provide Configure and ConfigureServices methods, instead of or in addition to
specifying a Startup class (which must also define these methods - see Application Startup). Multiple calls to
ConfigureServices will append to one another; calls to Configure or UseStartup will replace previous settings.
Configuring a Host
The WebHostBuilder provides methods for setting most of the available configuration values for the host, which
can also be set directly using UseSetting and associated key. For example, to specify the application name:
new WebHostBuilder()
.UseSetting("applicationName", "MyApp")
Key: captureStartupErrors . Defaults to false . When false , errors during startup result in the host exiting. When
true , the host will capture any exceptions from the Startup class and attempt to start the server. It will display an
error page (generic, or detailed, based on the Detailed Errors setting, below) for every request. Set using the
CaptureStartupErrors method.
new WebHostBuilder()
.CaptureStartupErrors(true)
Key: contentRoot . Defaults to the folder where the application assembly resides (for Kestrel; IIS will use the web
project root by default). This setting determines where ASP.NET Core will begin searching for content files, such as
MVC Views. Also used as the base path for the Web Root Setting. Set using the UseContentRoot method. Path must
exist, or host will fail to start.
new WebHostBuilder()
.UseContentRoot("c:\\mywebsite")
Key: detailedErrors . Defaults to false . When true (or when Environment is set to "Development"), the app will
display details of startup exceptions, instead of just a generic error page. Set using UseSetting .
new WebHostBuilder()
.UseSetting("detailedErrors", "true")
When Detailed Errors is set to false and Capture Startup Errors is true , a generic error page is displayed in
response to every request to the server.
When Detailed Errors is set to true and Capture Startup Errors is true , a detailed error page is displayed in
response to every request to the server.
Environment string
Key: environment . Defaults to "Production". May be set to any value. Framework-defined values include
"Development", "Staging", and "Production". Values are not case sensitive. See Working with Multiple
Environments. Set using the UseEnvironment method.
new WebHostBuilder()
.UseEnvironment("Development")
NOTE
By default, the environment is read from the ASPNETCORE_ENVIRONMENT environment variable. When using Visual Studio,
environment variables may be set in the launchSettings.json file.
Key: . Set to a semicolon (;) separated list of URL prefixes to which the server should respond. For example,
urls
http://localhost:123 . The domain/host name can be replaced with "*" to indicate the server should listen to
requests on any IP address or host using the specified port and protocol (for example, http://*:5000 or
https://*:5001 ). The protocol ( http:// or https:// ) must be included with each URL. The prefixes are
interpreted by the configured server; supported formats will vary between servers.
new WebHostBuilder()
.UseUrls("http://*:5000;http://localhost:5001;https://hostname:5002")
Startup Assembly string
Key: startupAssembly . Determines the assembly to search for the Startup class. Set using the UseStartup
method. May instead reference specific type using WebHostBuilder.UseStartup<StartupType> . If multiple UseStartup
methods are called, the last one takes precedence.
new WebHostBuilder()
.UseStartup("StartupAssemblyName")
Key: webroot . If not specified the default is (Content Root Path)\wwwroot , if it exists. If this path doesn't exist, then a
no-op file provider is used. Set using UseWebRoot .
new WebHostBuilder()
.UseWebRoot("public")
Overriding Configuration
Use Configuration to set configuration values to be used by the host. These values may be subsequently
overridden. This is specified using UseConfiguration .
host.Run();
}
In the example above, command-line arguments may be passed in to configure the host, or configuration settings
may optionally be specified in a hosting.json file. To specify the host run on a particular URL, you could pass in the
desired value from a command prompt:
The Run method starts the web app and blocks the calling thread until the host is shutdown.
host.Run();
You can run the host in a non-blocking manner by calling its Start method:
using (host)
{
host.Start();
Console.ReadLine();
}
Pass a list of URLs to the Start method and it will listen on the URLs specified:
using (host)
{
Console.ReadLine();
}
Ordering Importance
WebHostBuilder settings are first read from certain environment variables, if set. These environment variables
must use the format ASPNETCORE_{configurationKey} , so for example to set the URLs the server will listen on by
default, you would set ASPNETCORE_URLS .
You can override any of these environment variable values by specifying configuration (using UseConfiguration )
or by setting the value explicitly (using UseUrls for instance). The host will use whichever option sets the value
last. For this reason, UseIISIntegration must appear after UseUrls , because it replaces the URL with one
dynamically provided by IIS. If you want to programmatically set the default URL to one value, but allow it to be
overridden with configuration, you could configure the host as follows:
Additional resources
Publishing to IIS
Publish to a Linux Production Environment
Hosting ASP.NET Core as a Windows Service
Hosting ASP.NET Core Embedded in Another Application
Using Apache Web Server as a reverse-proxy
Introduction to session and application state in
ASP.NET Core
3/22/2017 10 min to read Edit on GitHub
Session state
Session state is a feature in ASP.NET Core that you can use to save and store user data while the user browses
your web app. Consisting of a dictionary or hash table on the server, session state persists data across requests
from a browser. The session data is backed by a cache.
ASP.NET Core maintains session state by giving the client a cookie that contains the session ID, which is sent to the
server with each request. The server uses the session ID to fetch the session data. Because the session cookie is
specific to the browser, you cannot share sessions across browsers. Session cookies are deleted only when the
browser session ends. If a cookie is received for an expired session, a new session that uses the same session
cookie is created.
The server retains a session for a limited time after the last request. You can either set the session timeout or use
the default value of 20 minutes. Session state is ideal for storing user data that is specific to a particular session
but doesnt need to be persisted permanently. Data is deleted from the backing store either when you call
Session.Clear or when the session expires in the data store. The server does not know when the browser is closed
or when the session cookie is deleted.
WARNING
Do not store sensitive data in session. The client might not close the browser and clear the session cookie (and some
browsers keep session cookies alive across windows). Also, a session might not be restricted to a single user; the next user
might continue with the same session.
The in-memory session provider stores session data on the local server. If you plan to run your web app on a
server farm, you must use sticky sessions to tie each session to a specific server. The Windows Azure Web Sites
platform defaults to sticky sessions (Application Request Routing or ARR). However, sticky sessions can affect
scalability and complicate web app updates. A better option is to use the Redis or SQL Server distributed caches,
which don't require sticky sessions. For more information, see Working with a Distributed Cache. For details on
setting up service providers, see Configuring Session later in this article.
The remainder of this section describes the options for storing user data.
TempData
ASP.NET Core MVC exposes the TempData property on a controller. This property stores data for only a single
request after the current one. TempData is particularly useful for redirection, when data is needed for more than a
single request. TempData is built on top of session state.
The cookie data is encoded with the Base64UrlTextEncoder. Because the cookie is encrypted and chunked, the
single cookie size limit does not apply. The cookie data is not compressed, because compressing encryped data
can lead to security problems such as the CRIME and BREACH attacks. For more information on the cookie-based
TempData provider, see CookieTempDataProvider.
Query strings
You can pass a limited amount of data from one request to another by adding it to the new requests query string.
This is useful for capturing state in a persistent manner that allows links with embedded state to be shared
through email or social networks. However, for this reason, you should never use query strings for sensitive data.
In addition to being easily shared, including data in query strings can create opportunities for Cross-Site Request
Forgery (CSRF) attacks, which can trick users into visiting malicious sites while authenticated. Attackers can then
steal user data from your app or take malicious actions on behalf of the user. Any preserved application or session
state must protect against CSRF attacks. For more information on CSRF attacks, see Preventing Cross-Site Request
Forgery (XSRF/CSRF) Attacks in ASP.NET Core.
Post data and hidden fields
Data can be saved in hidden form fields and posted back on the next request. This is common in multipage forms.
However, because the client can potentially tamper with the data, the server must always revalidate it.
Cookies
Cookies provide a way to store user-specific data in web applications. Because cookies are sent with every request,
their size should be kept to a minimum. Ideally, only an identifier should be stored in a cookie with the actual data
stored on the server. Most browsers restrict cookies to 4096 bytes. In addition, only a limited number of cookies
are available for each domain.
Because cookies are subject to tampering, they must be validated on the server. Although the durability of the
cookie on a client is subject to user intervention and expiration, they are generally the most durable form of data
persistence on the client.
Cookies are often used for personalization, where content is customized for a known user. Becasuse the user is
only identified and not authenticated in most cases, you can typically secure a cookie by storing the user name,
account name, or a unique user ID (such as a GUID) in the cookie. You can then use the cookie to access the user
personalization infrastructure of a site.
HttpContext.Items
The Items collection is a good location to store data that is needed only while processing one particular request.
The collection's contents are discarded after each request. The Items collection is best used as a way for
components or middleware to communicate when they operate at different points in time during a request and
have no direct way to pass parameters. For more information, see Working with HttpContext.Items, later in this
article.
Cache
Caching is an efficient way to store and retrieve data. You can control the lifetime of cached items based on time
and other considerations. Learn more about Caching.
Configuring Session
The Microsoft.AspNetCore.Session package provides middleware for managing session state. To enable the
session middleware, Startup must contain:
Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing
store for session.
AddSession call, which requires NuGet package "Microsoft.AspNetCore.Session".
UseSession call.
The following code shows how to set up the in-memory session provider.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using System;
services.AddSession(options =>
{
// Set a short timeout for easy testing.
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.CookieHttpOnly = true;
});
}
You can reference Session from HttpContext once it is installed and configured.
If you try to access Session before UseSession has been called, the exception
InvalidOperationException: Session has not been configured for this application or request is thrown.
If you try to create a new Session (that is, no session cookie has been created) after you have already begun
writing to the Response stream, the exception
InvalidOperationException: The session cannot be established after the response has started is thrown. The
exception can be found in the web server log; it will not be displayed in the browser.
Loading Session asynchronously
The default session provider in ASP.NET Core loads the session record from the underlying IDistributedCache
store asynchronously only if the ISession.LoadAsync method is explicitly called before the TryGetValue , Set , or
Remove methods. If LoadAsync is not called first, the underlying session record is loaded synchronously, which
could potentially impact the ability of the app to scale.
To have applications enforce this pattern, wrap the DistributedSessionStore and DistributedSession
implementations with versions that throw an exception if the LoadAsync method is not called before TryGetValue ,
Set , or Remove . Register the wrapped versions in the services container.
Implementation Details
Session uses a cookie to track and identify requests from a single browser. By default, this cookie is named
".AspNet.Session", and it uses a path of "/". Because the cookie default does not specify a domain, it is not made
available to the client-side script on the page (because CookieHttpOnly defaults to true ).
To override session defaults, use SessionOptions :
services.AddSession(options =>
{
options.CookieName = ".AdventureWorks.Session";
options.IdleTimeout = TimeSpan.FromSeconds(10);
});
}
The server uses the IdleTimeout property to determine how long a session can be idle before its contents are
abandoned. This property is independent of the cookie expiration. Each request that passes through the Session
middleware (read from or written to) resets the timeout.
Because Session is non-locking, if two requests both attempt to modify the contents of session, the last one
overrides the first. Session is implemented as a coherent session, which means that all the contents are stored
together. Two requests that are modifying different parts of the session (different keys) might still impact each
other.
If you add the following extension methods, you can set and get serializable objects to Session:
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
The following sample shows how to set and get a serializable object:
Note: Keys into Items are simple strings. If you are developing middleware that must work across many
applications, consider giving your keys a prefix with a unique identifier to avoid key collisions (for example,
"MyComponent.isVerified" instead of "isVerified").
Kestrel
Kestrel is the web server that is included by default in ASP.NET Core new-project templates. If your application
accepts requests only from an internal network, you can use Kestrel by itself.
If you expose your application to the Internet, we recommend that you use IIS, Nginx, or Apache as a reverse
proxy server. A reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after
some preliminary handling, as shown in the following diagram.
The most important reason for using a reverse proxy for edge deployments (exposed to traffic from the Internet)
is security. Kestrel is relatively new and does not yet have a full complement of defenses against attacks. This
includes but isn't limited to appropriate timeouts, size limits, and concurrent connection limits. For more
information about when to use Kestrel with a reverse proxy, see Kestrel.
You can't use IIS, Nginx, or Apache without Kestrel or a custom server implementation. ASP.NET Core was
designed to run in its own process so that it can behave consistently across platforms. IIS, Nginx, and Apache
dictate their own startup process and environment; to use them directly, ASP.NET Core would have to adapt to
the needs of each one. Using a web server implementation such as Kestrel gives ASP.NET Core control over the
startup process and environment. So rather than trying to adapt ASP.NET Core to IIS, Nginx, or Apache, you just
set up those web servers to proxy requests to Kestrel. This arrangement allows your Program.Main and Startup
classes to be essentially the same no matter where you deploy.
IIS with Kestrel
When you use IIS or IIS Express as a reverse proxy for ASP.NET Core, the ASP.NET Core application runs in a
process separate from the IIS worker process. In the IIS process, a special IIS module runs to coordinate the
reverse proxy relationship. This is the ASP.NET Core Module. The primary functions of the ASP.NET Core Module
are to start the ASP.NET Core application, restart it when it crashes, and forward HTTP traffic to it. For more
information, see ASP.NET Core Module.
Nginx with Kestrel
For information about how to use Nginx on Linux as a reverse proxy server for Kestrel, see Publish to a Linux
Production Environment.
Apache with Kestrel
For information about how to use Apache on Linux as a reverse proxy server for Kestrel, see Using Apache Web
Server as a reverse proxy.
WebListener
If you run your ASP.NET Core app on Windows, WebListener is an alternative that you can use for scenarios
where you want to expose your app to the Internet but you can't use IIS.
WebListener can also be used in place of Kestrel for applications that are exposed only to an internal network, if
you need one of its features that Kestrel doesn't support.
For internal network scenarios, Kestrel is generally recommended for best performance, but in some scenarios
you might want to use a feature that only WebListener offers. For information about WebListener features, see
WebListener.
Custom servers
You can create custom server implementations to use in place of Kestrel or WebListener. The Open Web Interface
for .NET (OWIN) guide demonstrates how to write a Nowin-based IServer implementation. You're free to
implement just the feature interfaces your application needs, though at a minimum you must support
IHttpRequestFeature and IHttpResponseFeature .
Next steps
For more information, see the following resources:
Kestrel
Kestrel with IIS
Kestrel with Nginx
Kestrel with Apache
WebListener
Introduction to Kestrel web server implementation in
ASP.NET Core
3/7/2017 4 min to read Edit on GitHub
If you expose your application to the Internet, you must use IIS, Nginx, or Apache as a reverse proxy server. A
reverse proxy server receives HTTP requests from the Internet and forwards them to Kestrel after some
preliminary handling.
A reverse proxy is required for edge deployments (exposed to traffic from the Internet) for security reasons.
Kestrel is relatively new and does not yet have a full complement of defenses against attacks. This includes but
isn't limited to appropriate timeouts, size limits, and concurrent connection limits.
Another scenario that requires a reverse proxy is when you have multiple applications that share the same port
running on a single server. That doesn't work with Kestrel directly because Kestrel doesn't support sharing a port
between multiple processes. When you configure Kestrel to listen on a port, it handles all traffic for that port
regardless of host header. A reverse proxy that can share ports must then forward to Kestrel on a unique port.
Even if a reverse proxy server isn't required, using one can simplify load balancing and SSL set-up -- only your
reverse proxy server requires an SSL certificate, and that server can communicate with your application servers
on the internal network using plain HTTP.
return 0;
}
URL prefixes
By default ASP.NET Core binds to http://localhost:5000 . You can configure URL prefixes and ports for Kestrel to
listen on by using the UseUrls extension method, the urls command-line argument, or the ASP.NET Core
configuration system. For more information about these methods, see Hosting. For information about how URL
binding works when you use IIS as a reverse proxy, see ASP.NET Core Module.
URL prefixes for Kestrel can be in any of the following formats.
IPv4 address with port number
http://65.55.39.10:80/
https://65.55.39.10:443/
http://[0:0:0:0:0:ffff:4137:270a]:80/
https://[0:0:0:0:0:ffff:4137:270a]:443/
http://contoso.com:80/
http://*:80/
https://contoso.com:443/
https://*:443/
Host names, *, and +, are not special. Anything that is not a recognized IP address or "localhost" will bind
to all IPv4 and IPv6 IPs. If you need to bind different host names to different ASP.NET Core applications on
the same port, use WebListener or a reverse proxy server such as IIS, Nginx, or Apache.
"Localhost" name with port number or loopback IP with port number
http://localhost:5000/
http://127.0.0.1:5000/
http://[::1]:5000/
When localhost is specified, Kestrel tries to bind to both IPv4 and IPv6 loopback interfaces. If the
requested port is in use by another service on either loopback interface, Kestrel fails to start. If either
loopback interface is unavailable for any other reason (most commonly because IPv6 is not supported),
Kestrel logs a warning.
Unix socket
http://unix:/run/dan-live.sock
If you specify port number 0, Kestrel dynamically binds to an available port. Binding to port 0 is allowed for any
host name or IP except for localhost name.
When you specify port 0, you can use IServerAddressesFeature to determine which port Kestrel actually bound to
at runtime. The following example gets the bound port and displays it on the console.
app.UseStaticFiles();
if (serverAddressesFeature != null)
{
await context.Response
.WriteAsync("<p>Listening on the following addresses: " +
string.Join(", ", serverAddressesFeature.Addresses) +
"</p>");
}
NOTE
HTTPS and HTTP cannot be hosted on the same port.
Next steps
For more information, see the following resources:
Sample app for this article
Kestrel source code
Your First ASP.NET Core Application on a Mac Using Visual Studio Code.
The tutorial uses Kestrel by itself locally, then deploys the app to Azure where it runs under Windows
using IIS as a reverse proxy server.
Introduction to ASP.NET Core Module
3/3/2017 4 min to read Edit on GitHub
Requests come in from the Web and hit the kernel mode Http.Sys driver which routes into IIS on the primary port
(80) or SSL port (443). The request is then forwarded to the ASP.NET Core application on the HTTP port
configured for the application, which is not port 80/443. Kestrel picks up the request and pushes it into the
ASP.NET Core middleware pipeline which then handles the request and passes it on as an HttpContext instance to
application logic. The application's response is then passed back to IIS, which pushes it back out to the HTTP client
that initiated the request.
ANCM has a few other functions as well:
Sets environment variables.
Logs stdout output to file storage.
Forwards Windows authentication tokens.
return 0;
}
The UseIISIntegration method looks for environment variables that ANCM sets, and it does nothing if they aren't
found. This behavior facilitates scenarios like developing and testing on MacOS and deploying to a server that
runs IIS. While running on the Mac, Kestrel acts as the web server, but when the app is deployed to the IIS
environment, it automatically hooks up to ANCM and IIS.
Don't call UseUrls
ANCM generates a dynamic port to assign to the back-end process. IWebHostBuilder.UseIISIntegration picks up
this dynamic port and configures Kestrel to listen on http://locahost:{dynamicPort}/ . This overwrites other URL
configurations like calls to IWebHostBuilder.UseUrls . Therefore, you don't need to call UseUrls when you use
ANCM. When you run the app without IIS, it listens on the default port number at http://localhost:5000 .
If you need to set the port number for when you run the app without IIS, you can call UseURLs . When you run
without IIS, the port number that you provide to UseUrls will take effect because IISIntegration will do nothing.
But when you run with IIS, the port number specified by ANCM will override whatever you passed to UseUrls .
In ASP.NET Core 1.0, if you call UseUrls , do it before you call IISIntegration so that the ANCM-configured port
doesn't get overwritten. This calling order is not required in ASP.NET Core 1.1, because the ANCM setting will
always override UseUrls .
Configure ANCM options in Web.config
Configuration for the ASP.NET Core Module is stored in the Web.config file that is located in the application's root
folder. Settings in this file point to the startup command and arguments that start your ASP.NET Core app. For
sample Web.config code and guidance on configuration options, see ASP.NET Core Module Configuration
Reference.
Run with IIS Express in development
IIS Express can be launched by Visual Studio using the default profile defined by the ASP.NET Core templates.
Next steps
For more information, see the following resources:
Sample app for this article
ASP.NET Core Module source code
ASP.NET Core Module Configuration Reference
Publishing to IIS
WebListener web server implementation in ASP.NET
Core
3/7/2017 5 min to read Edit on GitHub
Because it's built on Http.Sys, WebListener doesn't require a reverse proxy server for protection against attacks.
Http.Sys is mature technology that protects against many kinds of attacks and provides the robustness, security,
and scalability of a full-featured web server. IIS itself runs as an HTTP listener on top of Http.Sys.
WebListener is also a good choice for internal deployments when you need one of the features it offers that you
can't get by using Kestrel.
How to use WebListener
Here's an overview of setup tasks for the host OS and your ASP.NET Core application.
Configure Windows Server
Install the version of .NET that your application requires, such as .NET Core or .NET Framework 4.5.1.
Preregister URL prefixes to bind to WebListener, and set up SSL certificates
If you don't preregister URL prefixes in Windows, you have to run your application with administrator
privileges. The only exception is if you bind to localhost using HTTP (not HTTPS) with a port number
greater than 1024; in that case administrator privileges aren't required.
For details, see How to preregister prefixes and configure SSL later in this article.
Open firewall ports to allow traffic to reach WebListener.
You can use netsh.exe or PowerShell cmdlets.
There are also Http.Sys registry settings.
Configure your ASP.NET Core application
Install the NuGet package Microsoft.AspNetCore.Server.WebListener. This also installs
Microsoft.Net.Http.Server as a dependency.
Call the UseWebListener extension method on WebHostBuilder in your Main method, specifying any
WebListener options and settings that you need, as shown in the following example:
return 0;
}
Make sure your application is not configured to run IIS or IIS Express.
In Visual Studio, the default launch profile is for IIS Express. To run the project as a console application you
have to manually change the selected profile, as shown in the following screen shot.
while (true)
{
var context = await listener.AcceptAsync();
byte[] bytes = Encoding.ASCII.GetBytes("Hello World: " + DateTime.Now);
context.Response.ContentLength = bytes.Length;
context.Response.ContentType = "text/plain";
Next steps
For more information, see the following resources:
Sample app for this article
WebListener source code
Hosting
Request Features in ASP.NET Core
3/17/2017 2 min to read Edit on GitHub
By Steve Smith
Web server features related to how HTTP requests and responses are handled have been factored into interfaces.
These interfaces are used by server implementations and middleware to create and modify the application's
hosting pipeline.
Feature interfaces
ASP.NET Core defines a number of HTTP feature interfaces in Microsoft.AspNetCore.Http.Features which are used
by servers to identify the features they support. The following feature interfaces handle requests and return
responses:
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
protocols 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
terminated 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 Managing Application State).
Feature collections
The Features property of HttpContext 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.
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
Open Web Interface for .NET (OWIN)
Introduction to Open Web Interface for .NET (OWIN)
3/3/2017 5 min to read Edit on GitHub
The sample signature returns a Task and accepts an IDictionary<string, object> as required by OWIN.
The following code shows how to add the OwinHello middleware (shown above) to the ASP.NET pipeline with the
UseOwin extension method.
You can configure other actions to take place within the OWIN pipeline.
NOTE
Response headers should only be modified prior to the first write to the response stream.
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
return OwinHello;
// do something after
});
});
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace NowinSample
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseNowin()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
namespace Microsoft.AspNetCore.Hosting
{
public static class NowinWebHostBuilderExtensions
{
public static IWebHostBuilder UseNowin(this IWebHostBuilder builder)
{
return builder.ConfigureServices(services =>
{
services.AddSingleton<IServer, NowinServer>();
});
}
With this in place, all that's required to run an ASP.NET application using this custom server to call the extension in
Program.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
namespace NowinSample
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseNowin()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
app.Run(context =>
{
return context.Response.WriteAsync("Hello World");
});
}
while (!webSocket.CloseStatus.HasValue)
{
// Echo anything we receive
await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count),
received.MessageType, received.EndOfMessage, CancellationToken.None);
await webSocket.CloseAsync(webSocket.CloseStatus.Value,
webSocket.CloseStatusDescription, CancellationToken.None);
}
}
This sample is configured using the same NowinServer as the previous one - the only difference is in how the
application is configured in its Configure method. A test using a simple websocket client demonstrates the
application:
OWIN environment
You can construct a OWIN environment using the HttpContext .
OWIN keys
OWIN depends on an IDictionary<string,object> object to communicate information throughout an HTTP
Request/Response exchange. ASP.NET Core implements the keys listed below. See the primary specification,
extensions, and 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[]>
KEY VALUE (TYPE) DESCRIPTION
owin.RequestBody Stream
owin.ResponseHeaders IDictionary<string,string[]>
owin.ResponseBody Stream
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
Opaque v0.3.0
KEY VALUE (TYPE) DESCRIPTION
opaque.Version String
opaque.Stream Stream
opaque.CallCancelled CancellationToken
WebSocket v0.3.0
KEY VALUE (TYPE) DESCRIPTION
websocket.Version String
websocket.AcceptAlt Non-spec
websocket.CallCancelled CancellationToken
Additional Resources
Middleware
Servers
Choose between ASP.NET and ASP.NET Core
3/3/2017 1 min to read Edit on GitHub
No matter the web application you are creating, ASP.NET has a solution for you: from enterprise web applications
targeting Windows Server, to small microservices targeting Linux containers, and everything in between.
ASP.NET Core
ASP.NET Core is a new open-source and cross-platform .NET framework for building modern cloud-based web
applications on Windows, Mac, or Linux.
ASP.NET
ASP.NET is a mature web platform that provides all the services that you require to build enterprise-class server-
based web applications using .NET on Windows.
Use MVC, or Web API Use Web Forms, SignalR, MVC, Web API, or Web Pages
Develop with Visual Studio or Visual Studio Code using C# Develop with Visual Studio using C#, VB or F#
Choose .NET Framework or .NET Core runtime Use .NET Framework runtime
ASP.NET scenarios
Websites
APIs
Real-time
Resources
Introduction to ASP.NET
Introduction to ASP.NET Core
Overview of ASP.NET Core MVC
3/3/2017 9 min to read Edit on GitHub
By Steve Smith
ASP.NET Core MVC is a rich framework for building web apps and APIs using the Model-View-Controller design
pattern.
This delineation of responsibilities helps you scale the application in terms of complexity because its easier to
code, debug, and test something (model, view, or controller) that has a single job (and follows the Single
Responsibility Principle). It's more difficult to update, test, and debug code that has dependencies spread across
two or more of these three areas. For example, user interface logic tends to change more frequently than business
logic. If presentation code and business logic are combined in a single object, you have to modify an object
containing business logic every time you change the user interface. This is likely to introduce errors and require
the retesting of all business logic after every minimal user interface change.
NOTE
Both the view and the controller depend on the model. However, the model depends on neither the view nor the controller.
This is one the key benefits of the separation. This separation allows the model to be built and tested independent of the
visual presentation.
Model Responsibilities
The Model in an MVC application represents the state of the application and any business logic or operations that
should be performed by it. Business logic should be encapsulated in the model, along with any implementation
logic for persisting the state of the application. Strongly-typed views will typically use ViewModel types specifically
designed to contain the data to display on that view; the controller will create and populate these ViewModel
instances from the model.
NOTE
There are many ways to organize the model in an app that uses the MVC architectural pattern. Learn more about some
different kinds of model types.
View Responsibilities
Views are responsible for presenting content through the user interface. They use the Razor view engine to embed
.NET code in HTML markup. There should be minimal logic within views, and any logic in them should relate to
presenting content. If you find the need to perform a great deal of logic in view files in order to display data from a
complex model, consider using a View Component, ViewModel, or view template to simplify the view.
Controller Responsibilities
Controllers are the components that handle user interaction, work with the model, and ultimately select a view to
render. In an MVC application, the view only displays information; the controller handles and responds to user
input and interaction. In the MVC pattern, the controller is the initial entry point, and is responsible for selecting
which model types to work with and which view to render (hence its name - it controls how the app responds to a
given request).
NOTE
Controllers should not be overly complicated by too many responsibilities. To keep controller logic from becoming overly
complex, use the Single Responsibility Principle to push business logic out of the controller and into the domain model.
TIP
If you find that your controller actions frequently perform the same kinds of actions, you can follow the Don't Repeat
Yourself principle by moving these common actions into filters.
Features
ASP.NET Core MVC includes the following features:
Routing
Model binding
Model validation
Dependency injection
Filters
Areas
Web APIs
Testability
Razor view engine
Strongly typed views
Tag Helpers
View Components
Routing
ASP.NET Core MVC is built on top of ASP.NET Core's routing, a powerful URL-mapping component that lets you
build applications that have comprehensible and searchable URLs. This enables you to define your application's
URL naming patterns that work well for search engine optimization (SEO) and for link generation, without regard
for how the files on your web server are organized. You can define your routes using a convenient route template
syntax that supports route value constraints, defaults and optional values.
Convention-based routing enables you to globally define the URL formats that your application accepts and how
each of those formats maps to a specific action method on given controller. When an incoming request is
received, the routing engine parses the URL and matches it to one of the defined URL formats, and then calls the
associated controller's action method.
Attribute routing enables you to specify routing information by decorating your controllers and actions with
attributes that define your application's routes. This means that your route definitions are placed next to the
controller and action with which they're associated.
[Route("api/[controller]")]
public class ProductsController : Controller
{
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
...
}
}
Model binding
ASP.NET Core MVC model binding converts client request data (form values, route data, query string parameters,
HTTP headers) into objects that the controller can handle. As a result, your controller logic doesn't have to do the
work of figuring out the incoming request data; it simply has the data as parameters to its action methods.
Model validation
ASP.NET Core MVC supports validation by decorating your model object with data annotation validation
attributes. The validation attributes are checked on the client side before values are posted to the server, as well as
on the server before the controller action is called.
using System.ComponentModel.DataAnnotations;
public class LoginViewModel
{
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
A controller action:
The framework will handle validating request data both on the client and on the server. Validation logic specified
on model types is added to the rendered views as unobtrusive annotations and is enforced in the browser with
jQuery Validation.
Dependency injection
ASP.NET Core has built-in support for dependency injection (DI). In ASP.NET Core MVC, controllers can request
needed services through their constructors, allowing them to follow the Explicit Dependencies Principle.
Your app can also use dependency injection in view files, using the @inject directive:
Filters
Filters help developers encapsulate cross-cutting concerns, like exception handling or authorization. Filters enable
running custom pre- and post-processing logic for action methods, and can be configured to run at certain points
within the execution pipeline for a given request. Filters can be applied to controllers or actions as attributes (or
can be run globally). Several filters (such as Authorize ) are included in the framework.
[Authorize]
public class AccountController : Controller
{
Areas
Areas provide a way to partition a large ASP.NET Core MVC Web app into smaller functional groupings. An area is
effectively an MVC structure inside an application. In an MVC project, logical components like Model, Controller,
and View are kept in different folders, and MVC uses naming conventions to create the relationship between these
components. For a large app, it may be advantageous to partition the app into separate high level areas of
functionality. For instance, an e-commerce app with multiple business units, such as checkout, billing, and search
etc. Each of these units have their own logical component views, controllers, and models.
Web APIs
In addition to being a great platform for building web sites, ASP.NET Core MVC has great support for building
Web APIs. You can build services that can reach a broad range of clients including browsers and mobile devices.
The framework includes support for HTTP content-negotiation with built-in support for formatting data as JSON
or XML. Write custom formatters to add support for your own formats.
Use link generation to enable support for hypermedia. Easily enable support for cross-origin resource sharing
(CORS) so that your Web APIs can be shared across multiple Web applications.
Testability
The framework's use of interfaces and dependency injection make it well-suited to unit testing, and the framework
includes features (like a TestHost and InMemory provider for Entity Framework) that make integration testing
quick and easy as well. Learn more about testing controller logic.
Razor view engine
ASP.NET Core MVC views use the Razor view engine to render views. Razor is a compact, expressive and fluid
template markup language for defining views using embedded C# code. Razor is used to dynamically generate
web content on the server. You can cleanly mix server code with client side content and code.
<ul>
@for (int i = 0; i < 5; i++) {
<li>List item @i</li>
}
</ul>
Using the Razor view engine you can define layouts, partial views and replaceable sections.
Strongly typed views
Razor views in MVC can be strongly typed based on your model. Controllers can pass a strongly typed model to
views enabling your views to have type checking and IntelliSense support.
For example, the following view defines a model of type IEnumerable<Product> :
@model IEnumerable<Product>
<ul>
@foreach (Product p in Model)
{
<li>@p.Name</li>
}
</ul>
Tag Helpers
Tag Helpers enable server side code to participate in creating and rendering HTML elements in Razor files. You can
use tag helpers to define custom tags (for example, <environment> ) or to modify the behavior of existing tags (for
example, <label> ). Tag Helpers bind to specific elements based on the element name and its attributes. They
provide the benefits of server-side rendering while still preserving an HTML editing experience.
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
LinkTagHelper can be used to create a link to the Login action of the AccountsController :
<p>
Thank you for confirming your email.
Please <a asp-controller="Account" asp-action="Login">Click here to Log in</a>.
</p>
The EnvironmentTagHelper can be used to include different scripts in your views (for example, raw or minified)
based on the runtime environment, such as Development, Staging, or Production:
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery">
</script>
</environment>
Tag Helpers provide an HTML-friendly development experience and a rich IntelliSense environment for creating
HTML and Razor markup. Most of the built-in Tag Helpers target existing HTML elements and provide server-side
attributes for the element.
View Components
View Components allow you to package rendering logic and reuse it throughout the application. They're similar to
partial views, but with associated logic.
Building your first ASP.NET Core MVC app with
Visual Studio
3/3/2017 1 min to read Edit on GitHub
This series of tutorials will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio.
1. Getting started
2. Adding a controller
3. Adding a view
4. Adding a model
5. Working with SQL Server LocalDB
6. Controller methods and views
7. Adding Search
8. Adding a New Field
9. Adding Validation
10. Examining the Details and Delete methods
Getting started with ASP.NET Core MVC and Visual
Studio
3/18/2017 2 min to read Edit on GitHub
By Rick Anderson
This tutorial will teach you the basics of building an ASP.NET Core MVC web app using Visual Studio 2017.
NOTE
See Your First ASP.NET Core Application on a Mac Using Visual Studio Code for a Mac tutorial.
For the Visual Studio 2015 version of this tutorial, see the VS 2015 version of ASP.NET Core documentation in PDF
format.
Visual Studio used a default template for the MVC project you just created. You have a working app right now by
entering a project name and selecting a few options. This is a simple starter project, and it's a good place to start,
Tap F5 to run the app in debug mode or Ctrl-F5 in non-debug mode.
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 is the standard hostname for your local computer.
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:
You can debug the app by tapping the IIS Express button
The default template gives you working Home, About and Contact links. The browser image above doesn't show
these links. Depending on the size of your browser, you might need to click the navigation icon to show them.
NEXT
Adding a controller
3/9/2017 6 min to read Edit on GitHub
By Rick Anderson
The Model-View-Controller (MVC) architectural pattern separates an app into three main components: Model,
View, and Controller. The MVC pattern helps you create apps that are more testable and easier to update than
traditional monolithic apps. MVC-based apps contain:
Models: Classes that represent the data of the app. The model classes 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. They retrieve model data and call view templates that
return a response. 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. For example,
http://localhost:1234/Home/About has route data of Home (the controller) and About (the action method to
call on the home controller). http://localhost:1234/Movies/Edit/5 is a request to edit the movie with ID=5
using the movie controller. We'll talk about route data later in the tutorial.
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 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 MVC project currently contains folders for the Controllers and Views. A Models folder will be added in a
later step.
In Solution Explorer, right-click Controllers > Add > New Item
Select MVC Controller Class
In the Add New Item dialog, enter HelloWorldController.
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
//
// GET: /HelloWorld/
//
// GET: /HelloWorld/Welcome/
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.
The first comment states this is an HTTP GET method that is invoked by appending "/HelloWorld/" to the base 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]
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 ( id ) 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...". For this URL, the controller is HelloWorld and Welcome is the action method. We
haven't used the [Parameters] part of the URL yet.
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 include 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.
// GET: /HelloWorld/Welcome/
// Requires using System.Text.Encodings.Web;
public string Welcome(string name, int numTimes = 1)
{
return HtmlEncoder.Default.Encode($"Hello {name}, NumTimes is: {numTimes}");
}
The code above uses HtmlEncoder.Default.Encode to protect the app from malicious input (namely JavaScript). It
also uses Interpolated Strings.
In Visual Studio, in non-debug mode (Ctrl+F5), you don't need to build the app after changing 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.
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:
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?}");
});
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.
P R E V IO U S NEXT
Adding a view
3/7/2017 8 min to read Edit on GitHub
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 Razor. Razor-based view templates have a .cshtml file extension. They
provide an elegant way to create HTML output using C#.
Currently the method returns a string with a message that is hard-coded in the controller class. In the
Index
HelloWorldController class, replace the Index method with the following code:
The Index method above returns a View object. It 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.
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, change the name if necessary to Index.cshtml.
Tap Add
Replace the contents of the Views/HelloWorld/Index.cshtml Razor view file with the following:
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
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, and Contact 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.
<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.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-
value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
@Html.Raw(JavaScriptSnippet.FullScript)
</head>
<body>
<nav 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=".navbar-
collapse">
<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-area="" asp-controller="Movies" asp-action="Index" class="navbar-brand">MvcMovie</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© 2017 - MvcMovie</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"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/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"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
WARNING
We haven't implemented the Movies controller yet, so if you click on that link, you'll get a 404 (Not found) error.
Save your changes and tap the About link. Notice how the title on the browser tab now displays About - Movie
App instead of About - Mvc Movie. Tap the Contact link and notice that it also displays Movie App. 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.
@{
ViewData["Title"] = "Movie List";
}
ViewData["Title"] = "Movie List"; in the code above sets the Title property of the ViewData dictionary to
"Movie List". The Title property is used in the <title> HTML element in the layout page:
Save your change and navigate to http://localhost:xxxx/HelloWorld . 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.
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.
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace MvcMovie.Controllers
{
public class HelloWorldController : Controller
{
public IActionResult Index()
{
return View();
}
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"] = "Welcome";
}
<h2>Welcome</h2>
<ul>
@for (int i = 0; i < (int)ViewData["NumTimes"]; i++)
{
<li>@ViewData["Message"]</li>
}
</ul>
Data is taken from the URL and passed to the controller using the MVC 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.
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.
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.
P R E V IO U S NEXT
Adding a model
3/16/2017 8 min to read Edit on GitHub
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.
Youll 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.
using System;
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 database 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.
In the Add MVC Dependencies dialog, select Minimal Dependencies, and select Add.
Visual Studio adds the dependencies needed to scaffold a controller. A ScaffoldingReadMe.txt file is created which
you can delete.
In Solution Explorer, right-click the Controllers folder > Add > Controller.
In the Add Scaffold dialog, tap MVC Controller with views, using Entity Framework > Add.
Add EF tooling
In Solution Explorer, right click the MvcMovie project > Edit MvcMovie.csproj.
Add the "Microsoft.EntityFrameworkCore.Tools.DotNet" NuGet package:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
</ItemGroup>
Note: The version numbers shown above were correct at the time of writing.
dotnet restore
dotnet ef migrations add Initial
dotnet ef database update
dotnet ef commands
dotnet (.NET Core) is a cross-platform implementation of .NET. You can read about it here.
dotnet restore : Downloads the NuGet packages specified in the .csproj file.
dotnet ef migrations add Initial Runs the Entity Framework .NET Core CLI migrations command and creates
the initial migration. The parameter "Initial" is arbitrary, but customary for the first (initial) database migration.
This operation creates the Data/Migrations/<date-time>_Initial.cs file containing the migration commands to
add (or drop) the Movie table to the database
dotnet ef database update Updates the database with the migration we just created
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.
In some locales you'll need to specify the date format. See the highlighted code below.
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
public decimal Price { get; set; }
}
}
Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional.
services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
}
The code above shows the movie database context being added to the Dependency Injection container.
Open the Controllers/MoviesController.cs file and examine the constructor:
The constructor uses Dependency Injection to inject the database context ( MvcMovieContext ) into the controller.
The database context is used in each of the CRUD methods in the controller.
// GET: Movies/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == 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";
}
<h2>Details</h2>
<div>
<h4>Movie</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ReleaseDate)
</dt>
<dd>
@Html.DisplayFor(model => model.ReleaseDate)
</dd>
<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>
</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 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 view, 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 views also pass a Movie model object.
Examine the Index.cshtml view 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:
// GET: Movies
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 top of the Index.cshtml file:
@model IEnumerable<MvcMovie.Models.Movie>
The @modeldirective 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 view, 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.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</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>
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
P R E V IO U S NEXT
Working with SQL Server LocalDB
3/7/2017 2 min to read Edit on GitHub
By Rick Anderson
The MvcMovieContext object handles the task of connecting to the database and mapping Movie objects to
database records. The database context is registered with the Dependency Injection container in the
ConfigureServices method in the Startup.cs file:
services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
}
The ASP.NET Core Configuration system reads the ConnectionString . For local development, it gets the connection
string from the appsettings.json file:
"ConnectionStrings": {
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-20613a4b-deb5-4145-b6cc-
a5fd19afda13;Trusted_Connection=True;MultipleActiveResultSets=true"
}
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 for more information.
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
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 System;
using System.Linq;
namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<DbContextOptions<MvcMovieContext>>()))
{
// Look for any movies.
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
},
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.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
SeedData.Initialize(app.ApplicationServices);
}
}
}
NOTE
In Visual Studio 2017 RC you don't need to stop IIS Express.
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 (12:00:00
AM in the image below) and ReleaseDate should be two words.
Open the Models/Movie.cs file and add the highlighted lines shown below:
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { get; set; }
Right click on a red squiggly line > Quick Actions and Refactorings.
Tap using System.ComponentModel.DataAnnotations;
using System;
using System.ComponentModel.DataAnnotations;
namespace MvcMovie.Models
{
public class Movie
{
public int ID { get; set; }
public string Title { 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
(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.
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
information.
Open the Movies controller and examine the two Edit action methods. The following code shows the
HTTP GET Edit method, which fetchs the movie and populates the edit form generated by the Edit.cshtml Razor
file.
// GET: Movies/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price")] 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;
}
}
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.
// POST: Movies/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("ID,Title,ReleaseDate,Genre,Price")] 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;
}
}
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 with 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 method takes the movie ID parameter, looks up the movie using the Entity Framework
HttpGet Edit
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();
}
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="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"></span>
</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"></span>
</div>
</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"></span>
</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"></span>
</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.
@model MvcMovie.Models.Movie 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.
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.
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 [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 context. 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 in more detail. The
Validation Tag Helper in the Views/Movies/Edit.cshtml view template takes care of displaying appropriate error
messages.
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. 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 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
P R E V IO U S NEXT
Adding Search
3/10/2017 6 min to read Edit on GitHub
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 method with the following code:
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
The first line of the Index action method creates a LINQ query to select the movies:
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:
if (!String.IsNullOrEmpty(id))
{
movies = movies.Where(s => s.Title.Contains(id));
}
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 . Rather, query execution is deferred. That 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 in the c# code shown 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.
The rename targets are highlighted.
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!String.IsNullOrEmpty(id))
{
movies = movies.Where(s => s.Title.Contains(id));
}
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));
}
Open the Views/Movies/Index.cshtml file, and add the <form> markup highlighted below:
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<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;
}
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.
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.
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.
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace MvcMovie.Models
{
public class MovieGenreViewModel
{
public List<Movie> movies;
public SelectList genres;
public string movieGenre { get; set; }
}
}
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
if (!String.IsNullOrEmpty(movieGenre))
{
movies = movies.Where(x => x.Genre == movieGenre);
}
return View(movieGenreVM);
}
The following code is a LINQ query that retrieves all the genres from the database.
The SelectList of genres is created by projecting the distinct genres (we don't want our select list to have
duplicate genres).
@{
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.movies[0].Title)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].Price)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.movies)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</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>
Test the app by searching by genre, by movie title, and by both.
P R E V IO U S NEXT
Adding a New Field
3/7/2017 3 min to read Edit on GitHub
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 find inconsistent database/code issues.
[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">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.movies[0].Title)
</th>
<th>
@Html.DisplayNameFor(model => model.movies[0].ReleaseDate)
</th>
<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].Rating)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.movies)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.ReleaseDate)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rating)
</td>
<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 :
SqlException: Invalid column name 'Rating'.
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:
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 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.
P R E V IO U S NEXT
Adding validation
3/7/2017 9 min to read Edit on GitHub
By Rick Anderson
In 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 creates or edits a movie.
[Range(1, 100)]
[DataType(DataType.Currency)]
public decimal Price { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[Required]
[StringLength(30)]
public string Genre { get; set; }
[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]
[StringLength(5)]
[Required]
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.
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 follow code shows the two Create methods.
// GET: Movies/Create
public IActionResult Create()
{
return View();
}
// POST: Movies/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("ID,Title,ReleaseDate,Genre,Price, 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.
The following image shows how to disable JavaScript in the FireFox browser.
The following image shows how to disable JavaScript in the Chrome browser.
After you disable JavaScript, post invalid data and step through the debugger.
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 />
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 validation errors. See Validation for more
information.
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 honoring the DRY principle.
[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:
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
currency 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).
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:
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; }
[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
P R E V IO U S NEXT
Examining the Details and Delete methods
3/7/2017 3 min to read Edit on GitHub
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();
}
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?}");
});
EF 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 it 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();
}
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:
// GET: Movies/Delete/5
public async Task<IActionResult> Delete(int? id)
{
// POST: Movies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
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
parameter.)
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/6
[ValidateAntiForgeryToken]
public async Task<IActionResult> Delete(int id, bool notUsed)
Thanks for completing this introduction to ASP.NET Core MVC. We appreciate any comments you leave. Getting
started with MVC and EF Core is an excellent follow up to this tutorial.
P R E V IO U S
Building Your First Web API with ASP.NET Core MVC
and Visual Studio
3/14/2017 9 min to read Edit on GitHub
Overview
Here is the API that youll create:
GET /api/todo Get all to-do items None Array of to-do items
In the New ASP.NET Core Web Application (.NET Core) - TodoApi dialog, select the Web API template. Select
OK. Do not select Enable Docker Support.
Add support for Entity Framework Core
Install the Entity Framework Core InMemory database provider. This database provider allows Entity Framework
Core to be used with an in-memory database.
Edit the TodoApi.csproj file. In Solution Explorer, right-click the project. Select Edit TodoApi.csproj. In the
ItemGroup element, add the highlighted PackageReference :
namespace TodoApi.Models
{
public class TodoItem
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Key { get; set; }
public string Name { get; set; }
public bool IsComplete { get; set; }
}
}
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TodoApi.Models
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
}
}
}
namespace TodoApi.Models
{
public interface ITodoRepository
{
void Add(TodoItem item);
IEnumerable<TodoItem> GetAll();
TodoItem Find(long key);
void Remove(long key);
void Update(TodoItem item);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
namespace TodoApi.Models
{
public class TodoRepository : ITodoRepository
{
private readonly TodoContext _context;
In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs
file.
In the ConfigureServices method, add the highlighted code:
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 (and add closing braces):
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;
namespace TodoApi.Controllers
{
[Route("api/[controller]")]
public class TodoController : Controller
{
private readonly ITodoRepository _todoRepository;
This defines an empty controller class. In the next sections, we'll add methods to implement the API.
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
return _todoRepository.GetAll();
}
GET /api/todo/{id}
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 Postman.
Routing and URL paths
The [HttpGet] attribute specifies an HTTP GET method. The URL path for each method is constructed as follows:
Take the template string in the controllers 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 controller class name is TodoController and the root name is "todo". ASP.NET Core
routing is not case sensitive.
If the [HttpGet] attribute has a template string, append that to the path. This sample doesn't use a template
string.
In the GetById method:
"{id}" is a placeholder variable for the ID of the todo item. When GetById is invoked, it assigns the value of "{id}"
in the URL to the method's id parameter.
Name = "GetTodo" creates a named route and allows you to link to this route in an HTTP Response. I'll explain it with
an example later. See Routing to Controller Actions for detailed information.
Return values
The GetAll method returns an IEnumerable . 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 wide range of
return types. 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
[HttpPost]
public IActionResult Create([FromBody] TodoItem item)
{
if (item == null)
{
return BadRequest();
}
_todoRepository.Add(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
creates a new resource on the server. CreatedAtRoute 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.
Use Postman to send a Create request
Select Send
Select the Headers tab in the lower pane and copy the Location header:
You can use the Location header URI to access the resource you just created. Recall the GetById method created
the "GetTodo" named route:
Update
[HttpPut("{id}")]
public IActionResult Update(long id, [FromBody] TodoItem item)
{
if (item == null || item.Key != id)
{
return BadRequest();
}
todo.IsComplete = item.IsComplete;
todo.Name = item.Name;
_todoRepository.Update(todo);
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 IActionResult Delete(long id)
{
var todo = _todoRepository.Find(id);
if (todo == null)
{
return NotFound();
}
_todoRepository.Remove(id);
return new NoContentResult();
}
The response is 204 (No Content).
Next steps
To learn about creating a backend for a native mobile app, see Creating Backend Services for Native Mobile
Applications.
Routing to Controller Actions
For information about deploying your API, see Publishing and Deployment.
View or download sample code
Postman
Fiddler
Getting started with ASP.NET Core and Entity
Framework Core using Visual Studio
3/16/2017 1 min to read Edit on GitHub
This series of tutorials teaches you how to create ASP.NET Core MVC web applications that use Entity Framework
Core for data access. The tutorials require Visual Studio 2015.
1. Getting started
2. Create, Read, Update, and Delete operations
3. Sorting, filtering, paging, and grouping
4. Migrations
5. Creating a complex data model
6. Reading related data
7. Updating related data
8. Handling concurrency conflicts
9. Inheritance
10. Advanced topics
Getting started with ASP.NET Core MVC and Entity
Framework Core using Visual Studio (1 of 10)
3/16/2017 20 min to read Edit on GitHub
NOTE
For the Visual Studio 2015 version of this tutorial, see the VS 2015 version of ASP.NET Core documentation in PDF format.
Prerequisites
Visual Studio 2017 with the ASP.NET and web development and .NET Core cross-platform development
workloads installed.
Troubleshooting
If you run into a problem you can't resolve, you can generally find the solution by comparing your code to the
completed project. For a list of common errors and how to solve them, see the Troubleshooting section of the last
tutorial in the series. If you don't find what you need there, you can post a question to StackOverflow.com for
ASP.NET Core or EF Core.
TIP
This is a series of 10 tutorials, each of which builds on what is done in earlier tutorials. Consider saving a copy of the project
after each successful tutorial completion. Then if you run into problems, you can start over from the previous tutorial
instead of going back to the beginning of the whole series.
<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.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-
value="absolute" />
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
</environment>
@Html.Raw(JavaScriptSnippet.FullScript)
</head>
<body>
<nav 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=".navbar-
collapse">
<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-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">Contoso
University</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-area="" asp-controller="Students" asp-action="Index">Students</a></li>
<li><a asp-area="" asp-controller="Courses" asp-action="Index">Courses</a></li>
<li><a asp-area="" asp-controller="Instructors" asp-action="Index">Instructors</a></li>
<li><a asp-area="" asp-controller="Departments" asp-action="Index">Departments</a></li>
</ul>
</div>
</div>
</nav>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© 2017 - Contoso University</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"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/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"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
In Views/Home/Index.cshtml, replace the contents of the file with the following code to replace the text about
ASP.NET and MVC with text about this application:
@{
ViewData["Title"] = "Home Page";
}
<div class="jumbotron">
<h1>Contoso University</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Welcome to Contoso University</h2>
<p>
Contoso University is a sample application that
demonstrates how to use Entity Framework Core in an
ASP.NET Core MVC web application.
</p>
</div>
<div class="col-md-4">
<h2>Build it from scratch</h2>
<p>You can build the application by following the steps in a series of tutorials.</p>
<p><a class="btn btn-default" href="https://docs.asp.net/en/latest/data/ef-mvc/intro.html">See the
tutorial »</a></p>
</div>
<div class="col-md-4">
<h2>Download it</h2>
<p>You can download the completed project from GitHub.</p>
<p><a class="btn btn-default" href="https://github.com/aspnet/Docs/tree/master/aspnet/data/ef-
mvc/intro/samples/cu-final">See project source code »</a></p>
</div>
</div>
Press CTRL+F5 to run the project or choose Debug > Start Without Debugging from the menu. You see the
home page with tabs for the pages you'll create in these tutorials.
Entity Framework Core NuGet packages
To add EF Core support to a project, install the database provider that you want to target. For this tutorial, install
the SQL Server provider: Microsoft.EntityFrameworkCore.SqlServer.
Install-Package Microsoft.EntityFrameworkCore.SqlServer
using System;
using System.Collections.Generic;
namespace ContosoUniversity.Models
{
public class Student
{
public int ID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
The ID property will become the primary key column of the database table that corresponds to this class. By
default, the Entity Framework interprets a property that's named ID or classnameID as the primary key.
The Enrollments property is a navigation property. Navigation properties hold other entities that are related to
this entity. In this case, the Enrollments property of a Student entity will hold all of the Enrollment entities that
are related to that Student entity. In other words, if a given Student row in the database has two related
Enrollment rows (rows that contain that student's primary key value in their StudentID foreign key column), that
Student entity's Enrollments navigation property will contain those two Enrollment entities.
If a navigation property can hold multiple entities (as in many-to-many or one-to-many relationships), its type
must be a list in which entries can be added, deleted, and updated, such as ICollection<T> . You can specify
ICollection<T> or a type such as List<T> or HashSet<T> . If you specify ICollection<T> , EF creates a
HashSet<T> collection by default.
The Enrollment entity
In the Models folder, create Enrollment.cs and replace the existing code with the following code:
namespace ContosoUniversity.Models
{
public enum Grade
{
A, B, C, D, F
}
The EnrollmentID property will be the primary key; this entity uses the classnameID pattern instead of ID by
itself as you saw in the Student entity. Ordinarily you would choose one pattern and use it throughout your data
model. Here, the variation illustrates that you can use either pattern. In a later tutorial, you'll see how using ID
without classname makes it easier to implement inheritance in the data model.
The Grade property is an enum . The question mark after the Grade type declaration indicates that the Grade
property is nullable. A grade that's null is different from a zero grade -- null means a grade isn't known or hasn't
been assigned yet.
The StudentID property is a foreign key, and the corresponding navigation property is Student . An Enrollment
entity is associated with one Student entity, so the property can only hold a single Student entity (unlike the
Student.Enrollments navigation property you saw earlier, which can hold multiple Enrollment entities).
The CourseID property is a foreign key, and the corresponding navigation property is Course . An Enrollment
entity is associated with one Course entity.
Entity Framework interprets a property as a foreign key property if it's named
<navigation property name><primary key property name> (for example, StudentID for the Student navigation
property since the Student entity's primary key is ID ). Foreign key properties can also be named simply
<primary key property name> (for example, CourseID since the Course entity's primary key is CourseID ).
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace ContosoUniversity.Models
{
public class Course
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int CourseID { get; set; }
public string Title { get; set; }
public int Credits { get; set; }
The Enrollments property is a navigation property. A Course entity can be related to any number of Enrollment
entities.
We'll say more about the DatabaseGenerated attribute in a later tutorial in this series. Basically, this attribute lets
you enter the primary key for the course rather than having the database generate it.
namespace ContosoUniversity.Data
{
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
This code creates a DbSet property for each entity set. In Entity Framework terminology, an entity set typically
corresponds to a database table, and an entity corresponds to a row in the table.
You could have omitted the DbSet<Enrollment> and DbSet<Course> statements and it would work the same. The
Entity Framework would include them implicitly because the Student entity references the Enrollment entity
and the Enrollment entity references the Course entity.
When the database is created, EF creates tables that have names the same as the DbSet property names.
Property names for collections are typically plural (Students rather than Student), but developers disagree about
whether table names should be pluralized or not. For these tutorials you'll override the default behavior by
specifying singular table names in the DbContext. To do that, add the following highlighted code after the last
DbSet property.
using ContosoUniversity.Models;
using Microsoft.EntityFrameworkCore;
namespace ContosoUniversity.Data
{
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
services.AddMvc();
}
The name of the connection string is passed in to the context by calling a method on a DbContextOptionsBuilder
object. For local development, the ASP.NET Core configuration system reads the connection string from the
appsettings.json file.
Add using statements for ContosoUniversity.Data and Microsoft.EntityFrameworkCore namespaces, and then
build the project.
using ContosoUniversity.Data;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Open the appsettings.json file and add a connection string as shown in the following example.
{
"ConnectionStrings": {
"DefaultConnection": "Server=
(localdb)\\mssqllocaldb;Database=ContosoUniversity1;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
using ContosoUniversity.Models;
using System;
using System.Linq;
namespace ContosoUniversity.Data
{
public static class DbInitializer
{
public static void Initialize(SchoolContext context)
{
context.Database.EnsureCreated();
The code checks if there are any students in the database, and if not, it assumes the database is new and needs to
be seeded with test data. It loads test data into arrays rather than List<T> collections to optimize performance.
In Startup.cs, modify the Configure method to call this seed method on application startup. First, add the context
to the method signature so that ASP.NET dependency injection can provide it to your DbInitializer class.
Then call your DbInitializer.Initialize method at the end of the Configure method.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
DbInitializer.Initialize(context);
Now the first time you run the application the database will be created and seeded with test data. Whenever you
change your data model, you can delete the database, update your seed method, and start afresh with a new
database the same way. In later tutorials you'll see how to modify the database when the data model changes,
without deleting and re-creating it.
When you click Add, the Visual Studio scaffolding engine creates a StudentsController.cs file and a set of
views (.cshtml files) that work with the controller.
(The scaffolding engine can also create the database context for you if you don't create it manually first as you
did earlier for this tutorial. You can specify a new context class in the Add Controller box by clicking the plus
sign to the right of Data context class. Visual Studio will then create your DbContext class as well as the
controller and views.)
You'll notice that the controller takes a SchoolContext as a constructor parameter.
namespace ContosoUniversity.Controllers
{
public class StudentsController : Controller
{
private readonly SchoolContext _context;
ASP.NET dependency injection will take care of passing an instance of SchoolContext into the controller. You
configured that in the Startup.cs file earlier.
The controller contains an Index action method, which displays all students in the database. The method gets a
list of students from the Students entity set by reading the Students property of the database context instance:
You'll learn about the asynchronous programming elements in this code later in the tutorial.
The Views/Students/Index.cshtml view displays this list in a table:
@model IEnumerable<ContosoUniversity.Models.Student>
@{
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.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstMidName)
</th>
<th>
@Html.DisplayNameFor(model => model.EnrollmentDate)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstMidName)
</td>
<td>
@Html.DisplayFor(modelItem => item.EnrollmentDate)
</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>
Press CTRL+F5 to run the project or choose Debug > Start Without Debugging from the menu.
Click the Students tab to see the test data that the DbInitializer.Initialize method inserted. Depending on how
narrow your browser window is, you'll see the Student tab link at the top of the page or you'll have to click the
navigation icon in the upper right corner to see the link.
View the Database
When you started the application, the DbInitializer.Initialize method calls EnsureCreated . EF saw that there
was no database and so it created one, then the remainder of the Initialize method code populated the
database with data. You can use SQL Server Object Explorer (SSOX) to view the database in Visual Studio.
Close the browser.
If the SSOX window isn't already open, select it from the View menu in Visual Studio.
In SSOX, click (localdb)\MSSQLLocalDB > Databases, and then click the entry for the database name that is in
the connection string in your appsettings.json file.
Expand the Tables node to see the tables in your database.
Right-click the Student table and click View Data to see the columns that were created and the rows that were
inserted into the table.
The .mdf and .ldf database files are in the C:Users folder.
Because you're calling EnsureCreated in the initializer method that runs on app start, you could now make a
change to the Student class , delete the database, run the application again, and the database would
automatically be re-created to match your change. For example, if you add an EmailAddress property to the
Student class, you'll see a new EmailAddress column in the re-created table.
Conventions
The amount of code you had to write in order for the Entity Framework to be able to create a complete database
for you is minimal because of the use of conventions, or assumptions that the Entity Framework makes.
The names of DbSet properties are used as table names. For entities not referenced by a DbSet property,
entity class names are used as table names.
Entity property names are used for column names.
Entity properties that are named ID or classnameID are recognized as primary key properties.
A property is interpreted as a foreign key property if it's named (for example, StudentID for the Student
navigation property since the Student entity's primary key is ID ). Foreign key properties can also be
named simply (for example, EnrollmentID since the Enrollment entity's primary key is EnrollmentID ).
Conventional behavior can be overridden. For example, you can explicitly specify table names, as you saw earlier
in this tutorial. And you can set column names and set any property as primary key or foreign key, as you'll see in
a later tutorial in this series.
Asynchronous code
Asynchronous programming is the default mode for ASP.NET Core and EF Core.
A web server has a limited number of threads available, and in high load situations all of the available threads
might be in use. When that happens, the server can't process new requests until the threads are freed up. With
synchronous code, many threads may be tied up while they aren't actually doing any work because they're
waiting for I/O to complete. With asynchronous code, when a process is waiting for I/O to complete, its thread is
freed up for the server to use for processing other requests. As a result, asynchronous code enables server
resources to be use more efficiently, and the server is enabled to handle more traffic without delays.
Asynchronous code does introduce a small amount of overhead at run time, but for low traffic situations the
performance hit is negligible, while for high traffic situations, the potential performance improvement is
substantial.
In the following code, the async keyword, Task<T> return value, await keyword, and ToListAsync method
make the code execute asynchronously.
The async keyword tells the compiler to generate callbacks for parts of the method body and to
automatically create the Task<IActionResult> object that is returned.
The return type Task<IActionResult> represents ongoing work with a result of type IActionResult .
The await keyword causes the compiler to split the method into two parts. The first part ends with the
operation that is started asynchronously. The second part is put into a callback method that is called when
the operation completes.
ToListAsync is the asynchronous version of the ToList extension method.
Some things to be aware of when you are writing asynchronous code that uses the Entity Framework:
Only statements that cause queries or commands to be sent to the database are executed asynchronously.
That includes, for example, ToListAsync , SingleOrDefaultAsync , and SaveChangesAsync . It does not include,
for example, statements that just change an IQueryable , such as
var students = context.Students.Where(s => s.LastName == "Davolio") .
An EF context is not thread safe: don't try to do multiple operations in parallel. When you call any async EF
method, always use the await keyword.
If you want to take advantage of the performance benefits of async code, make sure that any library
packages that you're using (such as for paging), also use async if they call any Entity Framework methods
that cause queries to be sent to the database.
For more information about asynchronous programming in .NET, see Async Overview.
Summary
You've now created a simple application that uses the Entity Framework Core and SQL Server Express LocalDB to
store and display data. In the following tutorial, you'll learn how to perform basic CRUD (create, read, update,
delete) operations.
NEXT
Create, Read, Update, and Delete - EF Core with
ASP.NET Core MVC tutorial (2 of 10)
3/22/2017 19 min to read Edit on GitHub
NOTE
It's a common practice to implement the repository pattern in order to create an abstraction layer between your controller
and the data access layer. To keep these tutorials simple and focused on teaching how to use the Entity Framework itself,
they don't use repositories. For information about repositories with EF, see the last tutorial in this series.
if (student == null)
{
return NotFound();
}
return View(student);
}
The Include and ThenInclude methods cause the context to load the Student.Enrollments navigation property,
and within each enrollment the Enrollment.Course navigation property. You'll learn more about these methods in
the reading related data tutorial.
The AsNoTracking method improves performance in scenarios where the entities returned will not be updated in
the current context's lifetime. You'll learn more about AsNoTracking at the end of this tutorial.
Route data
The key value that is passed to the Details method comes from route data. Route data is data that the model
binder found in a segment of the URL. For example, the default route specifies controller, action, and id segments:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
DbInitializer.Initialize(context);
In the following URL, the default route maps Instructor as the controller, Index as the action, and 1 as the id; these
are route data values.
http://localhost:1230/Instructor/Index/1?courseID=2021
The last part of the URL ("?courseID=2021") is a query string value. The model binder will also pass the ID value to
the Details method id parameter if you pass it as a query string value:
http://localhost:1230/Instructor/Index?id=1&CourseID=2021
In the Index page, hyperlink URLs are created by tag helper statements in the Razor view. In the following Razor
code, the id parameter matches the default route, so id is added to the route data.
<a href="/Students/Edit/6">Edit</a>
In the following Razor code, studentID doesn't match a parameter in the default route, so it's added as a query
string.
<a href="/Students/Edit?studentID=6">Edit</a>
For more information about tag helpers, see Tag helpers in ASP.NET Core.
Add enrollments to the Details view
Open Views/Students/Details.cshtml. Each field is displayed using DisplayNameFor and DisplayFor helper, as
shown in the following example:
<dt>
@Html.DisplayNameFor(model => model.LastName)
</dt>
<dd>
@Html.DisplayFor(model => model.LastName)
</dd>
After the last field and immediately before the closing </dl> tag, add the following code to display a list of
enrollments:
<dt>
@Html.DisplayNameFor(model => model.Enrollments)
</dt>
<dd>
<table class="table">
<tr>
<th>Course Title</th>
<th>Grade</th>
</tr>
@foreach (var item in Model.Enrollments)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Course.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Grade)
</td>
</tr>
}
</table>
</dd>
If code indentation is wrong after you paste the code, press CTRL-K-D to correct it.
This code loops through the entities in the Enrollments navigation property. For each enrollment, it displays the
course title and the grade. The course title is retrieved from the Course entity that's stored in the Course
navigation property of the Enrollments entity.
Run the application, select the Students tab, and click the Details link for a student. You see the list of courses
and grades for the selected student:
Update the Create page
In StudentsController.cs, modify the HttpPost Create method by adding a try-catch block and removing ID from
the Bind attribute.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
{
try
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(student);
}
This code adds the Student entity created by the ASP.NET MVC model binder to the Students entity set and then
saves the changes to the database. (Model binder refers to the ASP.NET MVC functionality that makes it easier for
you to work with data submitted by a form; a model binder converts posted form values to CLR types and passes
them to the action method in parameters. In this case, the model binder instantiates a Student entity for you using
property values from the Form collection.)
You removed ID from the Bind attribute because ID is the primary key value which SQL Server will set
automatically when the row is inserted. Input from the user does not set the ID value.
Other than the Bind attribute, the try-catch block is the only change you've made to the scaffolded code. If an
exception that derives from DbUpdateException is caught while the changes are being saved, a generic error
message is displayed. DbUpdateException exceptions are sometimes caused by something external to the
application rather than a programming error, so the user is advised to try again. Although not implemented in this
sample, a production quality application would log the exception. For more information, see the Log for insight
section in Monitoring and Telemetry (Building Real-World Cloud Apps with Azure).
The ValidateAntiForgeryToken attribute helps prevent cross-site request forgery (CSRF) attacks. The token is
automatically injected into the view by the FormTagHelper and is included when the form is submitted by the
user. The token is validated by the ValidateAntiForgeryToken attribute. For more information about CSRF, see
Anti-Request Forgery.
Security note about overposting
The Bind attribute that the scaffolded code includes on the Create method is one way to protect against
overposting in create scenarios. For example, suppose the Student entity includes a Secret property that you
don't want this web page to set.
Even if you don't have a Secret field on the web page, a hacker could use a tool such as Fiddler, or write some
JavaScript, to post a Secret form value. Without the Bind attribute limiting the fields that the model binder uses
when it creates a Student instance, the model binder would pick up that Secret form value and use it to create
the Student entity instance. Then whatever value the hacker specified for the Secret form field would be updated
in your database. The following image shows the Fiddler tool adding the Secret field (with the value "OverPost")
to the posted form values.
The value "OverPost" would then be successfully added to the Secret property of the inserted row, although you
never intended that the web page be able to set that property.
It's a security best practice to use the Include parameter with the Bind attribute to whitelist fields. It's also
possible to use the Exclude parameter to blacklist fields you want to exclude. The reason Include is more secure
is that when you add a new property to the entity, the new field is not automatically protected by an Exclude list.
You can prevent overposting in edit scenarios by reading the entity from the database first and then calling
TryUpdateModel , passing in an explicit allowed properties list. That is the method used in these tutorials.
An alternative way to prevent overposting that is preferred by many developers is to use view models rather than
entity classes with model binding. Include only the properties you want to update in the view model. Once the
MVC model binder has finished, copy the view model properties to the entity instance, optionally using a tool such
as AutoMapper. Use _context.Entry on the entity instance to set its state to Unchanged , and then set
Property("PropertyName").IsModified to true on each entity property that is included in the view model. This
method works in both edit and create scenarios.
Test the Create page
The code in Views/Students/Create.cshtml uses label , input , and span (for validation messages) tag helpers for
each field.
Run the page by selecting the Students tab and clicking Create New.
Enter names and an invalid date and click Create to see the error message.
This is server-side validation that you get by default; in a later tutorial you'll see how to add attributes that will
generate code for client-side validation also. The following highlighted code shows the model validation check in
the Create method.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(
[Bind("EnrollmentDate,FirstMidName,LastName")] Student student)
{
try
{
if (ModelState.IsValid)
{
_context.Add(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists " +
"see your system administrator.");
}
return View(student);
}
Change the date to a valid value and click Create to see the new student appear in the Index page.
These changes implement a security best practice to prevent overposting. The scaffolder generated a Bind
attribute and added the entity created by the model binder to the entity set with a Modified flag. That code is not
recommended for many scenarios because the Bind attribute clears out any pre-existing data in fields not listed
in the Include parameter.
The new code reads the existing entity and calls TryUpdateModel to update fields in the retrieved entity based on
user input in the posted form data. The Entity Framework's automatic change tracking sets the Modified flag on
the fields that are changed by form input. When the SaveChanges method is called, the Entity Framework creates
SQL statements to update the database row. Concurrency conflicts are ignored, and only the table columns that
were updated by the user are updated in the database. (A later tutorial shows how to handle concurrency
conflicts.)
As a best practice to prevent overposting, the fields that you want to be updateable by the Edit page are
whitelisted in the TryUpdateModel parameters. (The empty string preceding the list of fields in the parameter list is
for a prefix to use with the form fields names.) Currently there are no extra fields that you're protecting, but listing
the fields that you want the model binder to bind ensures that if you add fields to the data model in the future,
they're automatically protected until you explicitly add them here.
As a result of these changes, the method signature of the HttpPost Edit method is the same as the HttpGet Edit
method; therefore you've renamed the method EditPost .
Alternative HttpPost Edit code: Create and attach
The recommended HttpPost edit code ensures that only changed columns get updated and preserves data in
properties that you don't want included for model binding. However, the read-first approach requires an extra
database read, and can result in more complex code for handling concurrency conflicts. An alternative is to attach
an entity created by the model binder to the EF context and mark it as modified. (Don't update your project with
this code, it's only shown to illustrate an optional approach.)
public async Task<IActionResult> Edit(int id, [Bind("ID,EnrollmentDate,FirstMidName,LastName")] Student
student)
{
if (id != student.ID)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
ModelState.AddModelError("", "Unable to save changes. " +
"Try again, and if the problem persists, " +
"see your system administrator.");
}
}
return View(student);
}
You can use this approach when the web page UI includes all of the fields in the entity and can update any of
them.
The scaffolded code uses the create-and-attach approach but only catches DbUpdateConcurrencyException
exceptions and returns 404 error codes. The example shown catches any database update exception and displays
an error message.
Entity States
The database context keeps track of whether entities in memory are in sync with their corresponding rows in the
database, and this information determines what happens when you call the SaveChanges method. For example,
when you pass a new entity to the Add method, that entity's state is set to Added . Then when you call the
SaveChanges method, the database context issues a SQL INSERT command.
In a desktop application, state changes are typically set automatically. You read an entity and make changes to
some of its property values. This causes its entity state to automatically be changed to Modified . Then when you
call SaveChanges , the Entity Framework generates a SQL UPDATE statement that updates only the actual
properties that you changed.
In a web app, the DbContext that initially reads an entity and displays its data to be edited is disposed after a page
is rendered. When the HttpPost Edit action method is called, a new web request is made and you have a new
instance of the DbContext . If you re-read the entity in that new context, you simulate desktop processing.
But if you don't want to do the extra read operation, you have to use the entity object created by the model binder.
The simplest way to do this is to set the entity state to Modified as is done in the alternative HttpPost Edit code
shown earlier. Then when you call SaveChanges , the Entity Framework updates all columns of the database row,
because the context has no way to know which properties you changed.
If you want to avoid the read-first approach, but you also want the SQL UPDATE statement to update only the
fields that the user actually changed, the code is more complex. You have to save the original values in some way
(such as by using hidden fields) so that they are available when the HttpPost Edit method is called. Then you can
create a Student entity using the original values, call the Attach method with that original version of the entity,
update the entity's values to the new values, and then call SaveChanges .
Test the Edit page
Run the application and select the Students tab, then click an Edit hyperlink.
Change some of the data and click Save. The Index page opens and you see the changed data.
if (saveChangesError.GetValueOrDefault())
{
ViewData["ErrorMessage"] =
"Delete failed. Try again, and if the problem persists " +
"see your system administrator.";
}
return View(student);
}
This code accepts an optional parameter that indicates whether the method was called after a failure to save
changes. This parameter is false when the HttpGet Delete method is called without a previous failure. When it is
called by the HttpPost Delete method in response to a database update error, the parameter is true and an error
message is passed to the view.
The read-first approach to HttpPost Delete
Replace the HttpPost Delete action method (named DeleteConfirmed ) with the following code, which performs
the actual delete operation and catches any database update errors.
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var student = await _context.Students
.AsNoTracking()
.SingleOrDefaultAsync(m => m.ID == id);
if (student == null)
{
return RedirectToAction("Index");
}
try
{
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
This code retrieves the selected entity, then calls the Remove method to set the entity's status to Deleted . When
SaveChanges is called, a SQL DELETE command is generated.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
try
{
Student studentToDelete = new Student() { ID = id };
_context.Entry(studentToDelete).State = EntityState.Deleted;
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
catch (DbUpdateException /* ex */)
{
//Log the error (uncomment ex variable name and write a log.)
return RedirectToAction("Delete", new { id = id, saveChangesError = true });
}
}
If the entity has related data that should also be deleted, make sure that cascade delet