Table of Contents
Introduction
Your first application
Get the SDK
Hello World in C#
Create an ASP.NET Core project
MVC basics
Create a controller
Create models
Create a view
Add a service class
Use dependency injection
Finish the controller
Update the layout
Add external packages
Use a database
Connect to a database
Update the context
Create a migration
Create a new service class
Add more features
Add new to-do items
Complete items with a checkbox
Security and identity
1.1
1.2
1.2.1
1.2.2
1.2.3
1.3
1.3.1
1.3.2
1.3.3
1.3.4
1.3.5
1.3.6
1.3.7
1.4
1.5
1.5.1
1.5.2
1.5.3
1.5.4
1.6
1.6.1
1.6.2
1.7
2
Require authentication
Using identity in the application
Authorization with roles
More resources
Automated testing
Unit testing
Integration testing
Deploy the application
Deploy to Azure
Deploy with Docker
Conclusion
1.7.1
1.7.2
1.7.3
1.7.4
1.8
1.8.1
1.8.2
1.9
1.9.1
1.9.2
1.10
3
Introduction
The Little ASP.NET Core Book
by Nate Barbettini
Copyright © 2018. All rights reserved.
ISBN: 978-1-387-75615-5
Released under the Creative Commons Attribution 4.0 license. You are
free to share, copy, and redistribute this book in any format, or remix and
transform it for any purpose (even commercially). You must give
appropriate credit and provide a link to the license.
For more information, visit
https://creativecommons.org/licenses/by/4.0/
Introduction
Thanks for picking up The Little ASP.NET Core Book! I wrote this short
book to help developers and people interested in web programming
learn about ASP.NET Core, a new framework for building web
applications and APIs.
The Little ASP.NET Core Book is structured as a tutorial. You'll build an
application from start to finish and learn:
The basics of the MVC (Model-View-Controller) pattern
How front-end code (HTML, CSS, JavaScript) works together with
back-end code
What dependency injection is and why it's useful
How to read and write data to a database
How to add log-in, registration, and security
How to deploy the application to the web
4
Introduction
Don't worry, you don't need to know anything about ASP.NET Core (or
any of the above) to get started.
Before you begin
The code for the finished version of the application you'll build is
available on GitHub:
https://www.github.com/nbarbettini/little-aspnetcore-todo
Feel free to download it if you want to see the finished product, or
compare as you write your own code.
The book itself is updated frequently with bug fixes and new content. If
you're reading a PDF, e-book, or print version, check the official website
(littleasp.net/book) to see if there's an updated version available. The
very last page of the book contains version information and a changelog.
Reading in your own language
Thanks to some fantastic multilingual contributors, the Little ASP.NET
Core Book has been translated into other languages:
Turkish: https://sahinyanlik.gitbooks.io/kisa-asp-net-core-kitabi/
Chinese: https://windsting.github.io/little-aspnetcore-book/book/
Who this book is for
If you're new to programming, this book will introduce you to the
patterns and concepts used to build modern web applications. You'll
learn how to build a web app (and how the big pieces fit together) by
5
Introduction
building something from scratch! While this little book won't be able to
cover absolutely everything you need to know about programming, it'll
give you a starting point so you can learn more advanced topics.
If you already code in a backend language like Node, Python, Ruby, Go,
or Java, you'll notice a lot of familiar ideas like MVC, view templates, and
dependency injection. The code will be in C#, but it won't look too
different from what you already know.
If you're an ASP.NET MVC developer, you'll feel right at home! ASP.NET
Core adds some new tools and reuses (and simplifies) the things you
already know. I'll point out some of the differences below.
No matter what your previous experience with web programming, this
book will teach you everything you need to create a simple and useful
web application in ASP.NET Core. You'll learn how to build functionality
using backend and frontend code, how to interact with a database, and
how to deploy the app to the world.
What is ASP.NET Core?
ASP.NET Core is a web framework created by Microsoft for building web
applications, APIs, and microservices. It uses common patterns like MVC
(Model-View-Controller), dependency injection, and a request pipeline
comprised of middleware. It's open-source under the Apache 2.0 license,
which means the source code is freely available, and the community is
encouraged to contribute bug fixes and new features.
ASP.NET Core runs on top of Microsoft's .NET runtime, similar to the
Java Virtual Machine (JVM) or the Ruby interpreter. You can write
ASP.NET Core applications in a number of languages (C#, Visual Basic,
F#). C# is the most popular choice, and it's what I'll use in this book. You
can build and run ASP.NET Core applications on Windows, Mac, and
Linux.
6
Introduction
Why do we need another web
framework?
There are a lot of great web frameworks to choose from already:
Node/Express, Spring, Ruby on Rails, Django, Laravel, and many more.
What advantages does ASP.NET Core have?
Speed. ASP.NET Core is fast. Because .NET code is compiled, it
executes much faster than code in interpreted languages like
JavaScript or Ruby. ASP.NET Core is also optimized for
multithreading and asynchronous tasks. It's common to see a 5-10x
speed improvement over code written in Node.js.
Ecosystem. ASP.NET Core may be new, but .NET has been around
for a long time. There are thousands of packages available on NuGet
(the .NET package manager; think npm, Ruby gems, or Maven).
There are already packages available for JSON deserialization,
database connectors, PDF generation, or almost anything else you
can think of.
Security. The team at Microsoft takes security seriously, and
ASP.NET Core is built to be secure from the ground up. It handles
things like sanitizing input data and preventing cross-site request
forgery (CSRF) attacks, so you don't have to. You also get the
benefit of static typing with the .NET compiler, which is like having a
very paranoid linter turned on at all times. This makes it harder to do
something you didn't intend with a variable or chunk of data.
.NET Core and .NET Standard
Throughout this book, you'll be learning about ASP.NET Core (the web
framework). I'll occasionally mention the .NET runtime, the supporting
library that runs .NET code. If this already sounds like Greek to you, just
7
Introduction
skip to the next chapter!
You may also hear about .NET Core and .NET Standard. The naming gets
confusing, so here's a simple explanation:
.NET Standard is a platform-agnostic interface that defines features and
APIs. It's important to note that .NET Standard doesn't represent any
actual code or functionality, just the API definition. There are different
"versions" or levels of .NET Standard that reflect how many APIs are
available (or how wide the API surface area is). For example, .NET
Standard 2.0 has more APIs available than .NET Standard 1.5, which has
more APIs than .NET Standard 1.0.
.NET Core is the .NET runtime that can be installed on Windows, Mac, or
Linux. It implements the APIs defined in the .NET Standard interface with
the appropriate platform-specific code on each operating system. This is
what you'll install on your own machine to build and run ASP.NET Core
applications.
And just for good measure, .NET Framework is a different
implementation of .NET Standard that is Windows-only. This was the
only .NET runtime until .NET Core came along and brought .NET to Mac
and Linux. ASP.NET Core can also run on Windows-only .NET
Framework, but I won't touch on this too much.
If you're confused by all this naming, no worries! We'll get to some real
code in a bit.
A note to ASP.NET 4 developers
If you haven't used a previous version of ASP.NET, skip ahead to the
next chapter.
8
Introduction
ASP.NET Core is a complete ground-up rewrite of ASP.NET, with a focus
on modernizing the framework and finally decoupling it from
System.Web, IIS, and Windows. If you remember all the OWIN/Katana
stuff from ASP.NET 4, you're already halfway there: the Katana project
became ASP.NET 5 which was ultimately renamed to ASP.NET Core.
Because of the Katana legacy, the Startup class is front and center, and
there's no more Application_Start or Global.asax . The entire pipeline
is driven by middleware, and there's no longer a split between MVC and
Web API: controllers can simply return views, status codes, or data.
Dependency injection comes baked in, so you don't need to install and
configure a container like StructureMap or Ninject if you don't want to.
And the entire framework has been optimized for speed and runtime
efficiency.
Alright, enough introduction. Let's dive in to ASP.NET Core!
9
Your first application
Your first application
Ready to build your first web app with ASP.NET Core? You'll need to
gather a few things first:
Your favorite code editor. You can use Atom, Sublime, Notepad, or
whatever editor you prefer writing code in. If you don't have a favorite,
give Visual Studio Code a try. It's a free, cross-platform code editor that
has rich support for writing C#, JavaScript, HTML, and more. Just search
for "download visual studio code" and follow the instructions.
If you're on Windows, you can also use Visual Studio to build ASP.NET
Core applications. You'll need Visual Studio 2017 version 15.3 or later
(the free Community Edition is fine). Visual Studio has great code
completion and refactoring support for C#, although Visual Studio Code
is close behind.
The .NET Core SDK. Regardless of the editor or platform you're using,
you'll need to install the .NET Core SDK, which includes the runtime,
base libraries, and command line tools you need for building ASP.NET
Core applications. The SDK can be installed on Windows, Mac, or Linux.
Once you've decided on an editor, you'll need to get the SDK.
10
Get the SDK
Get the SDK
Search for "download .net core" and follow the instructions on
Microsoft's download page to get the .NET Core SDK. After the SDK has
finished installing, open up the Terminal (or PowerShell on Windows) and
use the dotnet command line tool (also called a CLI) to make sure
everything is working:
dotnet --version
2.1.104
You can get more information about your platform with the --info flag:
dotnet --info
.NET Command Line Tools (2.1.104)
Product Information:
Version: 2.1.104
Commit SHA-1 hash: 48ec687460
Runtime Environment:
OS Name: Mac OS X
OS Version: 10.13
(more details...)
If you see output like the above, you're ready to go!
11
Hello World in C#
Hello World in C#
Before you dive into ASP.NET Core, try creating and running a simple C#
application.
You can do this all from the command line. First, open up the Terminal
(or PowerShell on Windows). Navigate to the location you want to store
your projects, such as your Documents directory:
cd Documents
Use the dotnet command to create a new project:
dotnet new console -o CsharpHelloWorld
The dotnet new command creates a new .NET project in C# by default.
The console parameter selects a template for a console application (a
program that outputs text to the screen). The -o CsharpHelloWorld
parameter tells dotnet new to create a new directory called
CsharpHelloWorld for all the project files. Move into this new directory:
cd CsharpHelloWorld
dotnet new console creates a basic C# program that writes the text
Hello World! to the screen. The program is comprised of two files: a
project file (with a .csproj extension) and a C# code file (with a .cs
extension). If you open the former in a text or code editor, you'll see this:
CsharpHelloWorld.csproj
12
Hello World in C#
Exe
netcoreapp2.0
The project file is XML-based and defines some metadata about the
project. Later, when you reference other packages, those will be listed
here (similar to a package.json file for npm). You won't have to edit this
file by hand very often.
Program.cs
using System;
namespace CsharpHelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
static void Main is the entry point method of a C# program, and by
convention it's placed in a class (a type of code structure or module)
called Program . The using statement at the top imports the built-in
System classes from .NET and makes them available to the code in your
class.
From inside the project directory, use dotnet run to run the program.
You'll see the output written to the console after the code compiles:
dotnet run
13
Hello World in C#
Hello World!
That's all it takes to scaffold and run a .NET program! Next, you'll do the
same thing for an ASP.NET Core application.
14
Create an ASP.NET Core project
Create an ASP.NET Core project
If you're still in the directory you created for the Hello World sample,
move back up to your Documents or home directory:
cd ..
Next, create a new directory to store your entire project, and move into
it:
mkdir AspNetCoreTodo
cd AspNetCoreTodo
Next, create a new project with dotnet new , this time with some extra
options:
dotnet new mvc --auth Individual -o AspNetCoreTodo
cd AspNetCoreTodo
This creates a new project from the mvc template, and adds some
additional authentication and security bits to the project. (I'll cover
security in the Security and identity chapter.)
You might be wondering why you have a directory called
AspNetCoreTodo inside another directory called AspNetCoreTodo .
The top-level or "root" directory can contain one or more project
directories. The root directory is sometimes called a solution
directory. Later, you'll add more project directories side-by-side
with the AspNetCoreTodo project directory, all within a single root
solution directory.
15
Create an ASP.NET Core project
You'll see quite a few files show up in the new project directory. Once
you cd into the new directory, all you have to do is run the project:
dotnet run
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Instead of printing to the console and exiting, this program starts a web
server and waits for requests on port 5000.
Open your web browser and navigate to http://localhost:5000 . You'll
see the default ASP.NET Core splash page, which means your project is
working! When you're done, press Ctrl-C in the terminal window to stop
the server.
The parts of an ASP.NET Core project
The dotnet new mvc template generates a number of files and
directories for you. Here are the most important things you get out of
the box:
The Program.cs and Startup.cs files set up the web server and
ASP.NET Core pipeline. The Startup class is where you can add
middleware that handles and modifies incoming requests, and serves
things like static content or error pages. It's also where you add your
own services to the dependency injection container (more on this
later).
The Models, Views, and Controllers directories contain the
components of the Model-View-Controller (MVC) architecture.
You'll explore all three in the next chapter.
16
Create an ASP.NET Core project
The wwwroot directory contains static assets like CSS, JavaScript,
and image files. Files in wwwroot will be served as static content,
and can be bundled and minified automatically.
The appsettings.json file contains configuration settings ASP.NET
Core will load on startup. You can use this to store database
connection strings or other things that you don't want to hard-code.
Tips for Visual Studio Code
If you're using Visual Studio Code for the first time, here are a couple of
helpful tips to get you started:
Open the project root folder: In Visual Studio Code, choose File -
Open or File - Open Folder. Open the AspNetCoreTodo folder (the
root directory), not the inner project directory. If Visual Studio Code
prompts you to install missing files, click Yes to add them.
F5 to run (and debug breakpoints): With your project open, press F5
to run the project in debug mode. This is the same as dotnet run
on the command line, but you have the benefit of setting
breakpoints in your code by clicking on the left margin:
Lightbulb to fix problems: If your code contains red squiggles
(compiler errors), put your cursor on the code that's red and look for
the lightbulb icon on the left margin. The lightbulb menu will suggest
17
Create an ASP.NET Core project
common fixes, like adding a missing using statement to your code:
Compile quickly: Use the shortcut Command-Shift-B or Control-
Shift-B to run the Build task, which does the same thing as dotnet
build .
These tips apply to Visual Studio (not Code) on Windows too. If
you're using Visual Studio, you'll need to open the .csproj
project file directly. Visual Studio will later prompt you to save the
Solution file, which you should save in the root directory (the first
AspNetCoreTodo folder). You can also create an ASP.NET Core
project directly within Visual Studio using the templates in File -
New Project.
A note about Git
If you use Git or GitHub to manage your source code, now is a good time
to do git init and initialize a Git repository in the project root
directory:
cd ..
git init
Make sure you add a .gitignore file that ignores the bin and obj
directories. The Visual Studio template on GitHub's gitignore template
repo (https://github.com/github/gitignore) works great.
18
Create an ASP.NET Core project
There's plenty more to explore, so let's dive in and start building an
application!
19
MVC basics
MVC basics
In this chapter, you'll explore the MVC system in ASP.NET Core. MVC
(Model-View-Controller) is a pattern for building web applications that's
used in almost every web framework (Ruby on Rails and Express are
popular examples), plus frontend JavaScript frameworks like Angular.
Mobile apps on iOS and Android use a variation of MVC as well.
As the name suggests, MVC has three components: models, views, and
controllers. Controllers handle incoming requests from a client or web
browser and make decisions about what code to run. Views are
templates (usually HTML plus a templating language like Handlebars,
Pug, or Razor) that get data added to them and then are displayed to the
user. Models hold the data that is added to views, or data that is entered
by the user.
A common pattern for MVC code is:
The controller receives a request and looks up some information in a
database
The controller creates a model with the information and attaches it
to a view
The view is rendered and displayed in the user's browser
The user clicks a button or submits a form, which sends a new
request to the controller, and the cycle repeats
If you've worked with MVC in other languages, you'll feel right at home
in ASP.NET Core MVC. If you're new to MVC, this chapter will teach you
the basics and will help get you started.
What you'll build
20
MVC basics
The "Hello World" exercise of MVC is building a to-do list application. It's
a great project since it's small and simple in scope, but it touches each
part of MVC and covers many of the concepts you'd use in a larger
application.
In this book, you'll build a to-do app that lets the user add items to their
to-do list and check them off once complete. More specifically, you'll be
creating:
A web application server (sometimes called the "backend") using
ASP.NET Core, C#, and the MVC pattern
A database to store the user's to-do items using the SQLite database
engine and a system called Entity Framework Core
Web pages and an interface that the user will interact with via their
browser, using HTML, CSS, and JavaScript (called the "frontend")
A login form and security checks so each user's to-do list is kept
private
Sound good? Let's built it! If you haven't already created a new ASP.NET
Core project using dotnet new mvc , follow the steps in the previous
chapter. You should be able to build and run the project and see the
default welcome screen.
21
Create a controller
Create a controller
There are already a few controllers in the project's Controllers directory,
including the HomeController that renders the default welcome screen
you see when you visit http://localhost:5000 . You can ignore these
controllers for now.
Create a new controller for the to-do list functionality, called
TodoController , and add the following code:
Controllers/TodoController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace AspNetCoreTodo.Controllers
{
public class TodoController : Controller
{
// Actions go here
}
}
Routes that are handled by controllers are called actions, and are
represented by methods in the controller class. For example, the
HomeController includes three action methods ( Index , About , and
Contact ) which are mapped by ASP.NET Core to these route URLs:
localhost:5000/Home -> Index()
localhost:5000/Home/About -> About()
localhost:5000/Home/Contact -> Contact()
22
Create a controller
There are a number of conventions (common patterns) used by ASP.NET
Core, such as the pattern that FooController becomes /Foo , and the
Index action name can be left out of the URL. You can customize this
behavior if you'd like, but for now, we'll stick to the default conventions.
Add a new action called Index to the TodoController , replacing the //
Actions go here comment:
public class TodoController : Controller
{
public IActionResult Index()
{
// Get to-do items from database
// Put items into a model
// Render view using the model
}
}
Action methods can return views, JSON data, or HTTP status codes like
200 OK and 404 Not Found . The IActionResult return type gives you
the flexibility to return any of these from the action.
It's a best practice to keep controllers as lightweight as possible. In this
case, the controller will be responsible for getting the to-do items from
the database, putting those items into a model the view can understand,
and sending the view back to the user's browser.
Before you can write the rest of the controller code, you need to create a
model and a view.
23
Create models
Create models
There are two separate model classes that need to be created: a model
that represents a to-do item stored in the database (sometimes called an
entity), and the model that will be combined with a view (the MV in
MVC) and sent back to the user's browser. Because both of them can be
referred to as "models", I'll refer to the latter as a view model.
First, create a class called TodoItem in the Models directory:
Models/TodoItem.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace AspNetCoreTodo.Models
{
public class TodoItem
{
public Guid Id { get; set; }
public bool IsDone { get; set; }
[Required]
public string Title { get; set; }
public DateTimeOffset? DueAt { get; set; }
}
}
This class defines what the database will need to store for each to-do
item: an ID, a title or name, whether the item is complete, and what the
due date is. Each line defines a property of the class:
24
Create models
The Id property is a guid, or a globally unique identifier. Guids (or
GUIDs) are long strings of letters and numbers, like 43ec09f2-7f70-
4f4b-9559-65011d5781bb . Because guids are random and are
extremely unlikely to be accidentally duplicated, they are commonly
used as unique IDs. You could also use a number (integer) as a
database entity ID, but you'd need to configure your database to
always increment the number when new rows are added to the
database. Guids are generated randomly, so you don't have to worry
about auto-incrementing.
The IsDone property is a boolean (true/false value). By default, it
will be false for all new items. Later you'll use write code to switch
this property to true when the user clicks an item's checkbox in
the view.
The Title property is a string (text value). This will hold the name or
description of the to-do item. The [Required] attribute tells
ASP.NET Core that this string can't be null or empty.
The DueAt property is a DateTimeOffset , which is a C# type that
stores a date/time stamp along with a timezone offset from UTC.
Storing the date, time, and timezone offset together makes it easy to
render dates accurately on systems in different timezones.
Notice the ? question mark after the DateTimeOffset type? That marks
the DueAt property as nullable, or optional. If the ? wasn't included,
every to-do item would need to have a due date. The Id and IsDone
properties aren't marked as nullable, so they are required and will always
have a value (or a default value).
Strings in C# are always nullable, so there's no need to mark the
Title property as nullable. C# strings can be null, empty, or contain
text.
25
Create models
Each property is followed by get; set; , which is a shorthand way of
saying the property is read/write (or, more technically, it has a getter and
setter methods).
At this point, it doesn't matter what the underlying database technology
is. It could be SQL Server, MySQL, MongoDB, Redis, or something more
exotic. This model defines what the database row or entry will look like
in C# so you don't have to worry about the low-level database stuff in
your code. This simple style of model is sometimes called a "plain old C#
object" or POCO.
The view model
Often, the model (entity) you store in the database is similar but not
exactly the same as the model you want to use in MVC (the view model).
In this case, the TodoItem model represents a single item in the
database, but the view might need to display two, ten, or a hundred to-
do items (depending on how badly the user is procrastinating).
Because of this, the view model should be a separate class that holds an
array of TodoItem s:
Models/TodoViewModel.cs
namespace AspNetCoreTodo.Models
{
public class TodoViewModel
{
public TodoItem[] Items { get; set; }
}
}
Now that you have some models, it's time to create a view that will take
a TodoViewModel and render the right HTML to show the user their to-
do list.
26
Create models
27
Create a view
Create a view
Views in ASP.NET Core are built using the Razor templating language,
which combines HTML and C# code. (If you've written pages using
Handlebars moustaches, ERB in Ruby on Rails, or Thymeleaf in Java,
you've already got the basic idea.)
Most view code is just HTML, with the occasional C# statement added in
to pull data out of the view model and turn it into text or HTML. The C#
statements are prefixed with the @ symbol.
The view rendered by the Index action of the TodoController needs to
take the data in the view model (a sequence of to-do items) and display it
in a nice table for the user. By convention, views are placed in the
Views directory, in a subdirectory corresponding to the controller name.
The file name of the view is the name of the action with a .cshtml
extension.
Create a Todo directory inside the Views directory, and add this file:
Views/Todo/Index.cshtml
@model TodoViewModel
@{
ViewData["Title"] = "Manage your todo list";
}
At the very top of the file, the @model directive tells Razor which model
to expect this view to be bound to. The model is accessed through the
Model property.
Assuming there are any to-do items in Model.Items , the foreach
statement will loop over each to-do item and render a table row (
element) containing the item's name and due date. A checkbox is also
rendered that will let the user mark the item as complete.
The layout file
You might be wondering where the rest of the HTML is: what about the
tag, or the header and footer of the page? ASP.NET Core uses a
layout view that defines the base structure that every other view is
rendered inside of. It's stored in Views/Shared/_Layout.cshtml .
29
Create a view
The default ASP.NET Core template includes Bootstrap and jQuery in
this layout file, so you can quickly create a web application. Of course,
you can use your own CSS and JavaScript libraries if you'd like.
Customizing the stylesheet
The default template also includes a stylesheet with some basic CSS
rules. The stylesheet is stored in the wwwroot/css directory. Add a few
new CSS style rules to the bottom of the site.css file:
wwwroot/css/site.css
div.todo-panel {
margin-top: 15px;
}
table tr.done {
text-decoration: line-through;
color: #888;
}
You can use CSS rules like these to completely customize how your
pages look and feel.
ASP.NET Core and Razor can do much more, such as partial views and
server-rendered view components, but a simple layout and view is all
you need for now. The official ASP.NET Core documentation (at
https://docs.asp.net) contains a number of examples if you'd like to learn
more.
30
Add a service class
Add a service class
You've created a model, a view, and a controller. Before you use the
model and view in the controller, you also need to write code that will
get the user's to-do items from a database.
You could write this database code directly in the controller, but it's a
better practice to keep your code separate. Why? In a big, real-world
application, you'll have to juggle many concerns:
Rendering views and handling incoming data: this is what your
controller already does.
Performing business logic, or code and logic that's related to the
purpose and "business" of your application. In a to-do list
application, business logic means decisions like setting a default due
date on new tasks, or only displaying tasks that are incomplete.
Other examples of business logic include calculating a total cost
based on product prices and tax rates, or checking whether a player
has enough points to level up in a game.
Saving and retrieving items from a database.
Again, it's possible to do all of these things in a single, massive controller,
but that quickly becomes too hard to manage and test. Instead, it's
common to see applications split up into two, three, or more "layers" or
tiers that each handle one (and only one) concern. This helps keep the
controllers as simple as possible, and makes it easier to test and change
the business logic and database code later.
Separating your application this way is sometimes called a multi-tier or
n-tier architecture. In some cases, the tiers (layers) are isolated in
completely separate projects, but other times it just refers to how the
31
Add a service class
classes are organized and used. The important thing is thinking about
how to split your application into manageable pieces, and avoid having
controllers or bloated classes that try to do everything.
For this project, you'll use two application layers: a presentation layer
made up of the controllers and views that interact with the user, and a
service layer that contains business logic and database code. The
presentation layer already exists, so the next step is to build a service
that handles to-do business logic and saves to-do items to a database.
Most larger projects use a 3-tier architecture: a presentation layer,
a service logic layer, and a data repository layer. A repository is a
class that's only focused on database code (no business logic). In
this application, you'll combine these into a single service layer for
simplicity, but feel free to experiment with different ways of
architecting the code.
Create an interface
The C# language includes the concept of interfaces, where the definition
of an object's methods and properties is separate from the class that
actually contains the code for those methods and properties. Interfaces
make it easy to keep your classes decoupled and easy to test, as you'll
see here (and later in the Automated testing chapter). You'll use an
interface to represent the service that can interact with to-do items in
the database.
By convention, interfaces are prefixed with "I". Create a new file in the
Services directory:
Services/ITodoItemService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
32
Add a service class
namespace AspNetCoreTodo.Services
{
public interface ITodoItemService
{
Task GetIncompleteItemsAsync();
}
}
Note that the namespace of this file is AspNetCoreTodo.Services .
Namespaces are a way to organize .NET code files, and it's customary for
the namespace to follow the directory the file is stored in
( AspNetCoreTodo.Services for files in the Services directory, and so on).
Because this file (in the AspNetCoreTodo.Services namespace) references
the TodoItem class (in the AspNetCoreTodo.Models namespace), it needs
to include a using statement at the top of the file to import that
namespace. Without the using statement, you'll see an error like:
The type or namespace name 'TodoItem' could not be found (are you
missing a using directive or an assembly reference?)
Since this is an interface, there isn't any actual code here, just the
definition (or method signature) of the GetIncompleteItemsAsync
method. This method requires no parameters and returns a
Task .
If this syntax looks confusing, think: "a Task that contains an array
of TodoItems".
The Task type is similar to a future or a promise, and it's used here
because this method will be asynchronous. In other words, the method
may not be able to return the list of to-do items right away because it
needs to go talk to the database first. (More on this later.)
Create the service class
33
Add a service class
Now that the interface is defined, you're ready to create the actual
service class. I'll cover database code in depth in the Use a database
chapter, so for now you'll just fake it and always return two hard-coded
items:
Services/FakeTodoItemService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AspNetCoreTodo.Models;
namespace AspNetCoreTodo.Services
{
public class FakeTodoItemService : ITodoItemService
{
public Task GetIncompleteItemsAsync()
{
var item1 = new TodoItem
{
Title = "Learn ASP.NET Core",
DueAt = DateTimeOffset.Now.AddDays(1)
};
var item2 = new TodoItem
{
Title = "Build awesome apps",
DueAt = DateTimeOffset.Now.AddDays(2)
};
return Task.FromResult(new[] { item1, item2 });
}
}
}
This FakeTodoItemService implements the ITodoItemService interface
but always returns the same array of two TodoItem s. You'll use this to
test the controller and view, and then add real database code in Use a
database.
34
Add a service class
35
Use dependency injection
Use dependency injection
Back in the TodoController , add some code to work with the
ITodoItemService :
public class TodoController : Controller
{
private readonly ITodoItemService _todoItemService;
public TodoController(ITodoItemService todoItemService)
{
_todoItemService = todoItemService;
}
public IActionResult Index()
{
// Get to-do items from database
// Put items into a model
// Pass the view to a model and render
}
}
Since ITodoItemService is in the Services namespace, you'll also need
to add a using statement at the top:
using AspNetCoreTodo.Services;
The first line of the class declares a private variable to hold a reference to
the ITodoItemService . This variable lets you use the service from the
Index action method later (you'll see how in a minute).
The public TodoController(ITodoItemService todoItemService) line
defines a constructor for the class. The constructor is a special method
that is called when you want to create a new instance of a class (the
36
Use dependency injection
TodoController class, in this case). By adding an ITodoItemService
parameter to the constructor, you've declared that in order to create the
TodoController , you'll need to provide an object that matches the
ITodoItemService interface.
Interfaces are awesome because they help decouple (separate) the
logic of your application. Since the controller depends on the
ITodoItemService interface, and not on any specific class, it
doesn't know or care which class it's actually given. It could be the
FakeTodoItemService , a different one that talks to a live database,
or something else! As long as it matches the interface, the
controller can use it. This makes it really easy to test parts of your
application separately. I'll cover testing in detail in the Automated
testing chapter.
Now you can finally use the ITodoItemService (via the private variable
you declared) in your action method to get to-do items from the service
layer:
public IActionResult Index()
{
var items = await _todoItemService.GetIncompleteItemsAsync();
// ...
}
Remember that the GetIncompleteItemsAsync method returned a
Task ? Returning a Task means that the method won't
necessarily have a result right away, but you can use the await keyword
to make sure your code waits until the result is ready before continuing
on.
The Task pattern is common when your code calls out to a database or
an API service, because it won't be able to return a real result until the
database (or network) responds. If you've used promises or callbacks in
37
Use dependency injection
JavaScript or other languages, Task is the same idea: the promise that
there will be a result - sometime in the future.
If you've had to deal with "callback hell" in older JavaScript code,
you're in luck. Dealing with asynchronous code in .NET is much
easier thanks to the magic of the await keyword! await lets
your code pause on an async operation, and then pick up where it
left off when the underlying database or network request finishes.
In the meantime, your application isn't blocked, because it can
process other requests as needed. This pattern is simple but takes
a little getting used to, so don't worry if this doesn't make sense
right away. Just keep following along!
The only catch is that you need to update the Index method signature
to return a Task instead of just IActionResult , and
mark it as async :
public async Task Index()
{
var items = await _todoItemService.GetIncompleteItemsAsync();
// Put items into a model
// Pass the view to a model and render
}
You're almost there! You've made the TodoController depend on the
ITodoItemService interface, but you haven't yet told ASP.NET Core that
you want the FakeTodoItemService to be the actual service that's used
under the hood. It might seem obvious right now since you only have
one class that implements ITodoItemService , but later you'll have
multiple classes that implement the same interface, so being explicit is
necessary.
38
Use dependency injection
Declaring (or "wiring up") which concrete class to use for each interface
is done in the ConfigureServices method of the Startup class. Right
now, it looks something like this:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// (... some code)
services.AddMvc();
}
The job of the ConfigureServices method is adding things to the service
container, or the collection of services that ASP.NET Core knows about.
The services.AddMvc line adds the services that the internal ASP.NET
Core systems need (as an experiment, try commenting out this line). Any
other services you want to use in your application must be added to the
service container here in ConfigureServices .
Add the following line anywhere inside the ConfigureServices method:
services.AddSingleton();
This line tells ASP.NET Core to use the FakeTodoItemService whenever
the ITodoItemService interface is requested in a constructor (or
anywhere else).
AddSingleton adds your service to the service container as a singleton.
This means that only one copy of the FakeTodoItemService is created,
and it's reused whenever the service is requested. Later, when you write
a different service class that talks to a database, you'll use a different
approach (called scoped) instead. I'll explain why in the Use a database
chapter.
39
Use dependency injection
That's it! When a request comes in and is routed to the TodoController ,
ASP.NET Core will look at the available services and automatically supply
the FakeTodoItemService when the controller asks for an
ITodoItemService . Because the services are "injected" from the service
container, this pattern is called dependency injection.
40
Finish the controller
Finish the controller
The last step is to finish the controller code. The controller now has a list
of to-do items from the service layer, and it needs to put those items into
a TodoViewModel and bind that model to the view you created earlier:
Controllers/TodoController.cs
public async Task Index()
{
var items = await _todoItemService.GetIncompleteItemsAsync();
var model = new TodoViewModel()
{
Items = items
};
return View(model);
}
If you haven't already, make sure these using statements are at the top
of the file:
using AspNetCoreTodo.Services;
using AspNetCoreTodo.Models;
If you're using Visual Studio or Visual Studio Code, the editor will suggest
these using statements when you put your cursor on a red squiggly
line.
Test it out
41
Finish the controller
To start the application, press F5 (if you're using Visual Studio or Visual
Studio Code), or just type dotnet run in the terminal. If the code
compiles without errors, the server will start up on port 5000 by default.
If your web browser didn't open automatically, open it and navigate to
http://localhost:5000/todo. You'll see the view you created, with the
data pulled from your fake database (for now).
Although it's possible to go directly to http://localhost:5000/todo , it
would be nicer to add an item called My to-dos to the navbar. To do this,
you can edit the shared layout file.
42
Update the layout
Update the layout
The layout file at Views/Shared/_Layout.cshtml contains the "base"
HTML for each view. This includes the navbar, which is rendered at the
top of each page.
To add a new item to the navbar, find the HTML code for the existing
navbar items:
Views/Shared/_Layout.cshtml
Add your own item that points to the Todo controller instead of Home :
My to-dos
The asp-controller and asp-action attributes on the element
are called tag helpers. Before the view is rendered, ASP.NET Core
replaces these tag helpers with real HTML attributes. In this case, a URL
to the /Todo/Index route is generated and added to the element
43
Update the layout
as an href attribute. This means you don't have to hard-code the route
to the TodoController . Instead, ASP.NET Core generates it for you
automatically.
If you've used Razor in ASP.NET 4.x, you'll notice some syntax
changes. Instead of using @Html.ActionLink() to generate a link
to an action, tag helpers are now the recommended way to create
links in your views. Tag helpers are useful for forms, too (you'll see
why in a later chapter). You can learn about other tag helpers in
the documentation at https://docs.asp.net.
44
Add external packages
Add external packages
One of the big advantages of using a mature ecosystem like .NET is that
the number of third-party packages and plugins is huge. Just like other
package systems, you can download and install .NET packages that help
with almost any task or problem you can imagine.
NuGet is both the package manager tool and the official package
repository (at https://www.nuget.org). You can search for NuGet
packages on the web, and install them from your local machine through
the terminal (or the GUI, if you're using Visual Studio).
Install the Humanizer package
At the end of the last chapter, the to-do application displayed to-do
items like this:
The due date column is displaying dates in a format that's good for
machines (called ISO 8601), but clunky for humans. Wouldn't it be nicer
if it simply read "X days from now"?
You could write code yourself that converted an ISO 8601 date into a
human-friendly string, but fortunately, there's a faster way.
The Humanizer package on NuGet solves this problem by providing
methods that can "humanize" or rewrite almost anything: dates, times,
durations, numbers, and so on. It's a fantastic and useful open-source
45
Add external packages
project that's published under the permissive MIT license.
To add it to your project, run this command in the terminal:
dotnet add package Humanizer
If you peek at the AspNetCoreTodo.csproj project file, you'll see a new
PackageReference line that references Humanizer .
Use Humanizer in the view
To use a package in your code, you usually need to add a using
statement that imports the package at the top of the file.
Since Humanizer will be used to rewrite dates rendered in the view, you
can use it directly in the view itself. First, add a @using statement at the
top of the view:
Views/Todo/Index.cshtml
@model TodoViewModel
@using Humanizer
// ...
Then, update the line that writes the DueAt property to use Humanizer's
Humanize method:
@item.DueAt.Humanize() |
Now the dates are much more readable:
46
Add external packages
There are packages available on NuGet for everything from parsing XML
to machine learning to posting to Twitter. ASP.NET Core itself, under the
hood, is nothing more than a collection of NuGet packages that are
added to your project.
The project file created by dotnet new mvc includes a single
reference to the Microsoft.AspNetCore.All package, which is a
convenient "metapackage" that references all of the other
ASP.NET Core packages you need for a typical project. That way,
you don't need to have hundreds of package references in your
project file.
In the next chapter, you'll use another set of NuGet packages (a system
called Entity Framework Core) to write code that interacts with a
database.
47
Use a database
Use a database
Writing database code can be tricky. Unless you really know what you're
doing, it's a bad idea to paste raw SQL query strings into your application
code. An object-relational mapper (ORM) makes it easier to write code
that interacts with a database by adding a layer of abstraction between
your code and the database itself. Hibernate in Java and ActiveRecord in
Ruby are two well-known ORMs.
There are a number of ORMs for .NET, including one built by Microsoft
and included in ASP.NET Core by default: Entity Framework Core. Entity
Framework Core makes it easy to connect to a number of different
database types, and lets you use C# code to create database queries that
are mapped back into C# models (POCOs).
Remember how creating a service interface decoupled the
controller code from the actual service class? Entity Framework
Core is like a big interface over your database. Your C# code can
stay database-agnostic, and you can swap out different providers
depending on the underlying database technology.
Entity Framework Core can connect to relational databases like SQL
Server, PostgreSQL, and MySQL, and also works with NoSQL (document)
databases like Mongo. During development, you'll use SQLite in this
project to make things easy to set up.
48
Connect to a database
Connect to a database
There are a few things you need to use Entity Framework Core to
connect to a database. Since you used dotnet new and the MVC +
Individual Auth template to set your project, you've already got them:
The Entity Framework Core packages. These are included by default
in all ASP.NET Core projects.
A database (naturally). The app.db file in the project root directory
is a small SQLite database created for you by dotnet new . SQLite is
a lightweight database engine that can run without requiring you to
install any extra tools on your machine, so it's easy and quick to use
in development.
A database context class. The database context is a C# class that
provides an entry point into the database. It's how your code will
interact with the database to read and save items. A basic context
class already exists in the Data/ApplicationDbContext.cs file.
A connection string. Whether you are connecting to a local file
database (like SQLite) or a database hosted elsewhere, you'll define
a string that contains the name or address of the database to
connect to. This is already set up for you in the appsettings.json
file: the connection string for the SQLite database is
DataSource=app.db .
Entity Framework Core uses the database context, together with the
connection string, to establish a connection to the database. You need to
tell Entity Framework Core which context, connection string, and
database provider to use in the ConfigureServices method of the
Startup class. Here's what's defined for you, thanks to the template:
services.AddDbContext(options =>
49
Connect to a database
options.UseSqlite(
Configuration.GetConnectionString("DefaultConnection")));
This code adds the ApplicationDbContext to the service container, and
tells Entity Framework Core to use the SQLite database provider, with
the connection string from configuration ( appsettings.json ).
As you can see, dotnet new creates a lot of stuff for you! The database
is set up and ready to be used. However, it doesn't have any tables for
storing to-do items. In order to store your TodoItem entities, you'll need
to update the context and migrate the database.
50
Update the context
Update the context
There's not a whole lot going on in the database context yet:
Data/ApplicationDbContext.cs
public class ApplicationDbContext
: IdentityDbContext
{
public ApplicationDbContext(
DbContextOptions options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// ...
}
}
Add a DbSet property to the ApplicationDbContext , right below the
constructor:
public ApplicationDbContext(
DbContextOptions options)
: base(options)
{
}
public DbSet Items { get; set; }
// ...
51
Update the context
A DbSet represents a table or collection in the database. By creating a
DbSet property called Items , you're telling Entity
Framework Core that you want to store TodoItem entities in a table
called Items .
You've updated the context class, but now there's one small problem: the
context and database are now out of sync, because there isn't actually an
Items table in the database. (Just updating the code of the context class
doesn't change the database itself.)
In order to update the database to reflect the change you just made to
the context, you need to create a migration.
If you already have an existing database, search the web for
"scaffold-dbcontext existing database" and read Microsoft's
documentation on using the Scaffold-DbContext tool to reverse-
engineer your database structure into the proper DbContext and
model classes automatically.
52
Create a migration
Create a migration
Migrations keep track of changes to the database structure over time.
They make it possible to undo (roll back) a set of changes, or create a
second database with the same structure as the first. With migrations,
you have a full history of modifications like adding or removing columns
(and entire tables).
In the previous chapter, you added an Items set to the context. Since
the context now includes a set (or table) that doesn't exist in the
database, you need to create a migration to update the database:
dotnet ef migrations add AddItems
This creates a new migration called AddItems by examining any changes
you've made to the context.
If you get an error like No executable found matching command
"dotnet-ef" , make sure you're in the right directory. These
commands must be run from the project root directory (where the
Program.cs file is).
If you open up the Data/Migrations directory, you'll see a few files:
53
Create a migration
The first migration file (with a name like 00_CreateIdentitySchema.cs )
was created and applied for you way back when you ran dotnet new .
Your new AddItem migration is prefixed with a timestamp when you
create it.
You can see a list of migrations with dotnet ef migrations list .
If you open your migration file, you'll see two methods called Up and
Down :
Data/Migrations/_AddItems.cs
protected override void Up(MigrationBuilder migrationBuilder)
{
// (... some code)
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
Id = table.Column(nullable: false),
DueAt = table.Column(nullable: true),
IsDone = table.Column(nullable: false),
Title = table.Column(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.Id);
});
// (some code...)
}
protected override void Down(MigrationBuilder migrationBuilder)
{
// (... some code)
migrationBuilder.DropTable(
name: "Items");
// (some code...)
}
54
Create a migration
The Up method runs when you apply the migration to the database.
Since you added a DbSet to the database context, Entity
Framework Core will create an Items table (with columns that match a
TodoItem ) when you apply the migration.
The Down method does the opposite: if you need to undo (roll back) the
migration, the Items table will be dropped.
Workaround for SQLite limitations
There are some limitations of SQLite that get in the way if you try to run
the migration as-is. Until this problem is fixed, use this workaround:
Comment out or remove the migrationBuilder.AddForeignKey lines
in the Up method.
Comment out or remove any migrationBuilder.DropForeignKey lines
in the Down method.
If you use a full-fledged SQL database, like SQL Server or MySQL, this
won't be an issue and you won't need to do this (admittedly hackish)
workaround.
Apply the migration
The final step after creating one (or more) migrations is to actually apply
them to the database:
dotnet ef database update
This command will cause Entity Framework Core to create the Items
table in the database.
55
Create a migration
If you want to roll back the database, you can provide the name of
the previous migration: dotnet ef database update
CreateIdentitySchema This will run the Down methods of any
migrations newer than the migration you specify.
If you need to completely erase the database and start over, run
dotnet ef database drop followed by dotnet ef database update
to re-scaffold the database and bring it up to the current
migration.
That's it! Both the database and the context are ready to go. Next, you'll
use the context in your service layer.
56
Create a new service class
Create a new service class
Back in the MVC basics chapter, you created a FakeTodoItemService that
contained hard-coded to-do items. Now that you have a database
context, you can create a new service class that will use Entity
Framework Core to get the real items from the database.
Delete the FakeTodoItemService.cs file, and create a new file:
Services/TodoItemService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AspNetCoreTodo.Data;
using AspNetCoreTodo.Models;
using Microsoft.EntityFrameworkCore;
namespace AspNetCoreTodo.Services
{
public class TodoItemService : ITodoItemService
{
private readonly ApplicationDbContext _context;
public TodoItemService(ApplicationDbContext context)
{
_context = context;
}
public async Task GetIncompleteItemsAsync()
{
return await _context.Items
.Where(x => x.IsDone == false)
.ToArrayAsync();
}
}
}
57
Create a new service class
You'll notice the same dependency injection pattern here that you saw in
the MVC basics chapter, except this time it's the ApplicationDbContext
that's getting injected. The ApplicationDbContext is already being added
to the service container in the ConfigureServices method, so it's
available for injection here.
Let's take a closer look at the code of the GetIncompleteItemsAsync
method. First, it uses the Items property of the context to access all the
to-do items in the DbSet :
var items = await _context.Items
Then, the Where method is used to filter only the items that are not
complete:
.Where(x => x.IsDone == false)
The Where method is a feature of C# called LINQ (language integrated
query), which takes inspiration from functional programming and makes
it easy to express database queries in code. Under the hood, Entity
Framework Core translates the Where method into a statement like
SELECT * FROM Items WHERE IsDone = 0 , or an equivalent query document
in a NoSQL database.
Finally, the ToArrayAsync method tells Entity Framework Core to get all
the entities that matched the filter and return them as an array. The
ToArrayAsync method is asynchronous (it returns a Task ), so it must be
await ed to get its value.
To make the method a little shorter, you can remove the intermediate
items variable and just return the result of the query directly (which
does the same thing):
public async Task GetIncompleteItemsAsync()
58
Create a new service class
{
return await _context.Items
.Where(x => x.IsDone == false)
.ToArrayAsync();
}
Update the service container
Because you deleted the FakeTodoItemService class, you'll need to
update the line in ConfigureServices that is wiring up the
ITodoItemService interface:
services.AddScoped();
AddScoped adds your service to the service container using the scoped
lifecycle. This means that a new instance of the TodoItemService class
will be created during each web request. This is required for service
classes that interact with a database.
Adding a service class that interacts with Entity Framework Core
(and your database) with the singleton lifecycle (or other lifecycles)
can cause problems, because of how Entity Framework Core
manages database connections per request under the hood. To
avoid that, always use the scoped lifecycle for services that
interact with Entity Framework Core.
The TodoController that depends on an injected ITodoItemService will
be blissfully unaware of the change in services classes, but under the
hood it'll be using Entity Framework Core and talking to a real database!
Test it out
Start up the application and navigate to http://localhost:5000/todo .
The fake items are gone, and your application is making real queries to
the database. There doesn't happen to be any saved to-do items, so it's
59
Create a new service class
blank for now.
In the next chapter, you'll add more features to the application, starting
with the ability to create new to-do items.
60
Add more features
Add more features
Now that you've connected to a database using Entity Framework Core,
you're ready to add some more features to the application. First, you'll
make it possible to add new to-do items using a form.
61
Add new to-do items
Add new to-do items
The user will add new to-do items with a simple form below the list:
Adding this feature requires a few steps:
Adding a form to the view
Creating a new action on the controller to handle the form
Adding code to the service layer to update the database
Add a form
The Views/Todo/Index.cshtml view has a placeholder for the Add Item
form:
To keep things separate and organized, you'll create the form as a partial
view. A partial view is a small piece of a larger view that lives in a
separate file.
Create an AddItemPartial.cshtml view:
Views/Todo/AddItemPartial.cshtml
62
Add new to-do items
@model TodoItem
The asp-action tag helper can generate a URL for the form, just like
when you use it on an element. In this case, the asp-action helper
gets replaced with the real path to the AddItem route you'll create: