Chapter 14. Building Web Applications Using ASP.NET Core MVC

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:

  • Understanding ASP.NET Core
  • Exploring an ASP.NET Core MVC web application
  • ASP.NET Core MVC controllers
  • ASP.NET Core MVC models
  • ASP.NET Core MVC views
  • Taking ASP.NET Core MVC further

Understanding ASP.NET Core

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:

  • Active Server Pages (ASP) was released in 1996, and was Microsoft's first attempt at a platform for dynamic server-side execution of web application code. ASP files are written in the VBScript language.
  • ASP.NET Web Forms was released in 2002 with the .NET Framework, and is designed to enable non-web developers, such as those familiar with Visual Basic, to quickly create web applications by dragging and dropping visual components and writing event-driven code in Visual Basic or C#. Web Forms can only be hosted on Windows, but is still used today in products such as Microsoft SharePoint. It should be avoided for new web projects in favor of ASP.NET Core.
  • Windows Communication Foundation (WCF) was released in 2006, and enables developers to build SOAP and REST services. SOAP is powerful but complex, so it should be avoided unless you need advanced features such as distributed transactions and complex messaging topologies.
  • ASP.NET MVC was released in 2009, and is designed to cleanly separate the concerns of web developers between the models that represent the data, the views that present that data, and the controllers that fetch the model and pass it to a view. This separation enables improved reuse and unit testing.
  • ASP.NET Web API was released in 2012, and enables developers to create HTTP aka REST services that are simpler and more scalable than SOAP services.
  • ASP.NET SignalR was released in 2013, and enables real-time communication in web applications by abstracting underlying technologies and techniques, such as Web Sockets and Long Polling.
  • ASP.NET Core was released in 2016 and combines MVC, Web API, and SignalR, running on the .NET Core. Therefore, it is cross-platform.

Tip

Good Practice

Choose ASP.NET Core to develop web applications and services because it includes three web-related technologies that are modern and cross-platform.

Classic ASP.NET versus modern ASP.NET Core

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.

Client-side web development

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:

  • HTML5: This is used for the content and structure of a web page
  • CSS3: This is used for the styles applied to elements on the web page
  • JavaScript: This is used for the procedural actions of the web page
  • Bower: This is a client-side package manager for the web

Note

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:

Note

Mads Kristensen wrote one of the most popular extensions for web development with Visual Studio 2010 and later named Web Essentials. It has now been broken up into smaller extensions that can be individually installed.

Understanding HTTP

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.

Tip

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:

  • On macOS, press Alt + Cmd + I
  • On Windows, press F2 or Ctrl + Shift + I

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:

Understanding HTTP

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:

Understanding HTTP

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:

Understanding HTTP

Note the following aspects:

  • Request Method is GET. Other methods that HTTP defines include POST, PUT, DELETE, HEAD, and PATCH.
  • Status Code is 200 OK. This means the server found the resource that the browser requested. Other status codes include 404 Missing.
  • Request Headers include Accept, which lists what formats the browser accepts. In this case, the browser is saying it understands HTML, XHTML, XML, and others.
  • Accept-Encoding header means the browser has told the server that it understands the GZIP and DEFLATE compression algorithms.
  • The browser has also told the server which human languages it would prefer: US English and then any dialect of English (with a quality value of 0.8).
  • I must have been to this site before because a Google Analytics cookie, named _ga, is being sent to the server so that it can track me.
  • The server has sent back the response compressed using the GZIP algorithm because it knows that the client can decompress that format.

Creating an ASP.NET Core project with Visual Studio 2017

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:

Creating an ASP.NET Core project with Visual Studio 2017

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.
  • The 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.
  • The wwwroot folder contains client-side files, such as CSS style sheets, images, and JavaScript libraries.
  • The 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.
  • There are two C# classes in the root folder: Program.cs and Startup.cs.
  • There are multiple configuration files. The old format used XML, for example Web.config, and the newer format uses JSON, for example appsettings.json, as shown in the following screenshot:

Creating an ASP.NET Core project with Visual Studio 2017

Performing database migrations

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:

Performing database migrations

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:

Note

Sometimes, you must drop down the menu twice for Visual Studio to populate the browser list!

Performing database migrations

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:

Performing database migrations

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:

Performing database migrations

Note that if you enter a password that is not strong enough, there is built-in validation.

Close Chrome.

Reviewing authentication with ASP.NET Identity

Use Server Explorer to add a database connection to the Ch14_WebApp database, as shown in the following screenshot:

Reviewing authentication with ASP.NET Identity

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:

Reviewing authentication with ASP.NET Identity

Tip

Good Practice

The ASP.NET Core web application project follows good practice by storing a hash of the password instead of the password itself. The ASP.NET Core Identity system can be extended to support two-factor authentication.

Creating an ASP.NET Core project with Visual Studio Code

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

Note

Options when creating a new ASP.NET Core MVC application include choosing the type of authentication to use, None or Individual, and choosing between SQL Server LocalDb and SQLite to store the users and roles.

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:

Creating an ASP.NET Core project with Visual Studio Code

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:

Creating an ASP.NET Core project with Visual Studio Code

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:

Creating an ASP.NET Core project with Visual Studio Code

Click Register and complete the form to register a new user.

Note

This ASP.NET Core web application project has the same behavior as the one created by Visual Studio 2017, except that it uses SQLite instead of SQL Server LocalDb for the ASP.NET Identity database.

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.

Managing client-side packages with Bower

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:

Managing client-side packages with Bower

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:

Managing client-side packages with Bower

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" 
      } 
    } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.27.251