This chapter is about building web applications with a modern HTTP architecture on the server side using Microsoft ASP.NET Core MVC. You will learn about the startup configuration, authentication, authorization, routes, models, views, and controllers that make up ASP.NET Core MVC.
This chapter will cover the following topics:
Microsoft ASP.NET Core is part of a history of Microsoft technologies used to build web applications and services that have evolved over the years:
ASP.NET celebrates its 15th birthday in 2017. It's a teenager!
Until now, it has been built on top of a large assembly in the .NET Framework named System.Web.dll
. Over the years, this assembly has accumulated a lot of features, many of which are not suitable for modern cross-platform development.
ASP.NET Core is a major redesign of ASP.NET. It removes the dependency on the System.Web.dll
assembly and is composed of modular lightweight packages, just like the rest of .NET Core.
You can develop and run ASP.NET Core applications cross-platform on Windows, macOS, and Linux. Microsoft has even created a cross-platform, super performant web server named Kestrel. The entire stack is open source, and it is designed to integrate with a variety of client-side tools and frameworks, including Bower, Gulp, Grunt, AngularJS, jQuery, and Bootstrap.
When building web applications, a developer needs to know more than just C# and .NET Core. On the client (that is, in the web browser), you will use a combination of the following components:
This book is about C#, so we will cover some of the basics of client-side web development, but for more detail, I recommend the book HTML5 Web Application Development By Example by Packt Publishing at https://www.packtpub.com/web-development/html5-web-application-development-example-beginners-guide.
To make it easier to work with HTML5, CSS3, and JavaScript, both Visual Studio 2017 and Visual Studio Code have extensions such as the ones listed here:
To communicate with a web server, the client makes calls over the network using a protocol known as HTTP (Hypertext Transfer Protocol). HTTP is the technical underpinning of the "Web". So, when we talk about web applications or web services, we mean they use HTTP to communicate between a client (often a web browser) and a server.
A client makes an HTTP request for a resource, such as a page identified by a URL (Uniform Resource Locator), and the server sends back an HTTP response. You can use Google Chrome and other browsers to record requests and responses.
Good Practice
Google Chrome is available on more operating systems than any other browser and it has powerful built-in developer tools, so it is a good first choice of browser. Always test your web application with Chrome and at least two other browsers, for example, Firefox and either Microsoft Edge for Windows 10 and Safari for macOS.
Start Google Chrome. To show developer tools in Chrome:
Click on the Network tab. Chrome should immediately start recording the network traffic between your browser and any web servers, as shown in the following screenshot:
In Chrome's address box, enter https://www.asp.net/get-started.
In the Developer Tools window, in the list of recorded requests, click on the first entry, as shown in the following screenshot:
On the right-hand side, click the Headers tab, and you will see details about the request and the response, as shown in the following screenshot:
Note the following aspects:
GET
. Other methods that HTTP defines include POST
, PUT
, DELETE
, HEAD
, and PATCH
.200 OK
. This means the server found the resource that the browser requested. Other status codes include 404 Missing
._ga
, is being sent to the server so that it can track me.In Visual Studio 2017, press Ctrl + Shift + N or choose File | New | Project....
In the New Project dialog, in the Installed | Templates list, expand Visual C#, and select .NET Core. In the center list, select ASP.NET Core Web Application (.NET Core), type the name as Ch14_WebApp
, type the solution name as Chapter14
, and then click on OK.
In the New ASP.NET Core Web Application (.NET Core) dialog box, select the Web Application template. Ensure that Authentication is set to Individual User Accounts by clicking the Change Authentication button. The Host in the cloud box should be left unchecked. Click OK, as shown in the following screenshot:
After a few seconds, your Solution Explorer window will look as shown in the following screenshot. Note the following points:
Dependencies
contain Bower packages on the client side and NuGet packages on the server side.Data
folder contains C# classes to perform initial database operations, known as migrations, to create the tables required to store users and roles for the authentication system.wwwroot
folder contains client-side files, such as CSS style sheets, images, and JavaScript libraries.Controllers
, Models
, and Views
folders contain ASP.NET Core classes and .cshtml
files for execution on the server. We will look at this in more detail later.Program.cs
and Startup.cs
.Web.config
, and the newer format uses JSON, for example appsettings.json
, as shown in the following screenshot:
Before we test the web application, we need to ensure that the database migrations have been executed.
Open the appsettings.json
file and note the database connection string. It should look something like this:
Server=(localdb)\mssqllocaldb;Database=aspnet-Ch14_WebApp-584f323f-
a60e-4933-9845-f67225753337;
Trusted_Connection=True;MultipleActiveResultSets=true
When the database migrations execute, it will create a database with the preceding name in Microsoft SQL Server LocalDb. You could modify the database name now to make it less GUID-y, for example, as in the following connection string:
Server=(localdb)\mssqllocaldb;Database=Ch14_WebApp;
Trusted_Connection=True;MultipleActiveResultSets=true
Right-click on the Ch14_WebApp
project and choose Open Folder in File Explorer.
Click in the address box and copy the path to the clipboard.
From the Windows Start menu, start Developer Command Prompt for Visual Studio 2017.
Change to the project directory and execute the database migrations by entering the following commands:
cd C:CodeChapter14srcCh14_WebApp dotnet ef database update
You should see output, as shown in the following screenshot:
In the Visual Studio 2017 toolbar, click the dropdown arrow next to IIS Express, choose Web Browser, and then Google Chrome, as shown in the following screenshot:
Run the application by pressing Ctrl + F5.
Note that your ASP.NET Core application is hosted in a cross-platform web server named Kestrel (here, integrated with IIS Express) using a random port number for local testing and that the sample ASP.NET Core web application project returns a site with half a dozen pages, including Home, About, Contact, Register, and Log in, as shown in the following screenshot:
Click on the Register link and then complete the form to create a new account in the database that was created by the migration, as shown in the following screenshot:
Note that if you enter a password that is not strong enough, there is built-in validation.
Close Chrome.
Use Server Explorer to add a database connection to the Ch14_WebApp
database, as shown in the following screenshot:
Right-click the AspNetUsers
table, and note the row that was added to the database when you completed the register form, as shown in the following screenshot:
Create a folder named Chapter14
with a subfolder named Ch14_WebApp
. In Visual Studio Code, open the Ch14_WebApp
folder. In the Integrated Terminal, enter the following command to review your options when creating an ASP.NET MVC application with the CLI tool:
dotnet new mvc --help
You will see the following output:
bash-3.2$ dotnet new mvc --help Template Instantiation Commands for .NET Core CLI. Usage: dotnet new [arguments] [options] Arguments: template The template to instantiate. Options: -l|--list List templates containing the specified name. -lang|--language Specifies the language of the template to create -n|--name The name for the output being created. If no name is specified, the name of th e current directory is used. -o|--output Location to place the generated output. -h|--help Displays help for this command. -all|--show-all Shows all templates ASP.NET Core Web App (C#) Author: Microsoft Options: -au|--auth The type of authentication to use None - No authentication Individual - Individual authentication Default: None -uld|--use-local-db Whether or not to use LocalDB instead of SQLite bool - Optional Default: false -f|--framework netcoreapp1.0 - Target netcoreapp1.0 netcoreapp1.1 - Target netcoreapp1.1 Default: netcoreapp1.1
At the Terminal prompt, enter the following command to create a new ASP.NET Core MVC web application project with individual user accounts for authentication, stored in SQLite:
dotnet new mvc --auth Individual
Note the folders and files created in the Explorer pane, as shown in the following screenshot, including some database migrations that must be executed to create the database for registering new users, as shown in the following screenshot:
Open the appsettings.json
file and note the database connection string. It should be something like this:
Data Source=.\Ch14_WebApp.db
When the database migrations execute, it will create a database with the preceding name in the current folder using SQLite.
In the Integrated Terminal, enter the following commands to restore packages and then execute the database migrations:
dotnet restore dotnet ef database update
In the Explorer pane, expand the bin
folder and note that the database named Ch14_WebApp.db
has been created.
If you installed an SQLite tool such as SQLiteStudio, then you could open the database and see the tables that the ASP.NET Identity system uses to register users and roles, as shown in the following screenshot:
In the Integrated Terminal, enter the following command:
dotnet run
You will see the following output:
bash-3.2$ dotnet run Hosting environment: Production Content root path: /Users/markjprice/Code/Chapter14/Ch14_WebApp Now listening on: http://localhost:5000 Application started. Press Ctrl+C to shut down.
Leave the web application running and start Chrome.
Navigate to http:/localhost:5000/
and view the results, as shown in the following screenshot:
Click Register and complete the form to register a new user.
Close Chrome, and in the Integrated Terminal, press Ctrl + C to stop the console application and shut down the Kestrel web server that is hosting your ASP.NET Core web application.
In the next section, we will use Bower to manage client-side packages, for example, Bootstrap and jQuery. Bower is not installed by default.
In Visual Studio Code, choose View | Extensions or press Shift + Cmd + X .
Search for bower
to find the most popular Bower extension, and click Install, as shown in the following screenshot:
Click Reload.
Navigate to View | Command Palette..., or press Shift + Cmd + P .
Enter the command Bower
, and then choose Bower Install to restore packages, as shown in the following screenshot:
Expand wwwroot
and note that the lib
folder has been created with four subfolders for the packages that are specified in the bower.json
file:
{ "name": "webapplication", "private": true, "dependencies": { "bootstrap": "3.3.6", "jquery": "2.2.3", "jquery-validation": "1.15.0", "jquery-validation-unobtrusive": "3.2.6" } }
18.216.27.251