In the previous chapters, I built quick and simple ASP.NET Core applications. I described ASP.NET Core patterns, the essential C# features, and the tools that good ASP.NET Core developers require. Now it is time to put everything together and build a simple but realistic e-commerce application.
My application, called SportsStore, will follow the classic approach taken by online stores everywhere. I will create an online product catalog that customers can browse by category and page, a shopping cart where users can add and remove products, and a checkout where customers can enter their shipping details. I will also create an administration area that includes create, read, update, and delete (CRUD) facilities for managing the catalog, and I will protect it so that only logged-in administrators can make changes.
My goal in this chapter and those that follow is to give you a sense of what real ASP.NET Core development is by creating as realistic an example as possible. I want to focus on ASP.NET Core, of course, so I have simplified the integration with external systems, such as the database, and omitted others entirely, such as payment processing.
You might find the going a little slow as I build up the levels of infrastructure I need, but the initial investment will result in maintainable, extensible, well-structured code with excellent support for unit testing.
I include sections on unit testing different components in the SportsStore application throughout the development process, demonstrating how to isolate and test different ASP.NET Core components.
I know that unit testing is not embraced by everyone. If you do not want to unit test, that is fine with me. To that end, when I have something to say that is purely about testing, I put it in a sidebar like this one. If you are not interested in unit testing, you can skip right over these sections, and the SportsStore application will work just fine. You do not need to do any kind of unit testing to get the technology benefits of ASP.NET Core, although, of course, support for testing is a key reason for adopting ASP.NET Core in many projects.
Most of the features I use for the SportsStore application have their own chapters later in the book. Rather than duplicate everything here, I tell you just enough to make sense of the example application and point you to another chapter for in-depth information.
I will call out each step needed to build the application so that you can see how the ASP.NET Core features fit together. You should pay particular attention when I create views. You will get some odd results if you do not follow the examples closely.
Creating the Projects
I am going to start with a minimal ASP.NET Core project and add the features I require as they are needed. Open a new PowerShell command prompt from the Windows Start menu and run the commands shown in Listing 7-1 to get started.
You can download the example project for this chapter—and for all the other chapters in this book—from https://github.com/apress/pro-asp.net-core-3. See Chapter 1 for how to get help if you have problems running the examples.
Creating the SportsStore Project
These commands create a SportsSln solution folder that contains a SportsStore project folder created with the web project template. The SportsSln folder also contains a solution file, to which the SportsStore project is added.
I am using different names for the solution and project folders to make the examples easier to follow, but if you create a project with Visual Studio, the default is to use the same name for both folders. There is no “right” approach, and you can use whatever names suit your project.
Creating the Unit Test Project
Creating the Unit Test Project
Installing the Moq Package
Creating the Application Project Folders
The Folders Created in Listing 7-3
Name | Description |
---|---|
Models | This folder will contain the data model and the classes that provide access to the data in the application’s database. |
Controllers | This folder will contain the controller classes that handle HTTP requests. |
Views | This folder will contain all the Razor files, grouped into separate subfolders. |
Views/Home | This folder will contain Razor files that are specific to the Home controller, which I create in the “Creating the Controller and View” section. |
Views/Shared | This folder will contain Razor files that are common to all controllers. |
Opening the Projects
Preparing the Application Services and the Request Pipeline
The Startup class is responsible for configuring the ASP.NET Core application. Apply the changes shown in Listing 7-4 to the Startup class in the SportsStore project to configure the basic application features.
The Startup class is an important ASP.NET Core feature. I describe it in detail in Chapter 12.
Configuring the Application in the Startup.cs File in the SportsStore Folder
The ConfigureServices method is used to set up objects, known as services, that can be used throughout the application and that are accessed through a feature called dependency injection, which I describe in Chapter 14. The AddControllersWithViews method called in the ConfigureServices method sets up the shared objects required by applications using the MVC Framework and the Razor view engine.
The Middleware Methods Used in Listing 7-4
Name | Description |
---|---|
UseDeveloperExceptionPage() | This extension method displays details of exceptions that occur in the application, which is useful during the development process, as described in Chapter 16. It should not be enabled in deployed applications, and I disable this feature when I prepare the SportsStore application for deployment in Chapter 11. |
UseStatusCodePages() | This extension method adds a simple message to HTTP responses that would not otherwise have a body, such as 404 - Not Found responses. This feature is described in Chapter 16. |
UseStaticFiles() | This extension method enables support for serving static content from the wwwroot folder. I describe the support for static content in Chapter 15. |
One especially important middleware component provides the endpoint routing feature, which matches HTTP requests to the application features - known as endpoints - able to produce responses for them, a process I describe in detail in Chapter 13. The endpoint routing feature is added to the request pipeline with the UseRouting and UseEndpoints methods. To register the MVC Framework as a source of endpoints, Listing 7-4 calls the MapDefaultControllerRoute method.
Configuring the Razor View Engine
The Razor view engine is responsible for processing view files, which have the .cshtml extension, to generate HTML responses. Some initial preparation is required to configure Razor to make it easier to create views for the application.
Add a Razor View Imports file named _ViewImports.cshtml in the Views folder with the content shown in Listing 7-5.
Pay close attention to the contents of this file. It is easy to make a mistake that causes the application to generate incorrect HTML content.
The Contents of the _ViewImports.cshtml File in the SportsStore/Views Folder
The @using statement will allow me to use the types in the SportsStore.Models namespace in views without needing to refer to the namespace. The @addTagHelper statement enables the built-in tag helpers, which I use later to create HTML elements that reflect the configuration of the SportsStore application and which I describe in detail in Chapter 15.
The Contents of the _ViewStart.cshtml File in the SportsStore/Views Folder
The Contents of the _Layout.cshtml File in the SportsStore/Views/Shared Folder
This file defines a simple HTML document into which the contents of other views will be inserted by the @RenderBody expression. I explain how Razor expressions work in detail in Chapter 21.
Creating the Controller and View
The Contents of the HomeController.cs File in the SportsStore/Controllers Folder
The MapDefaultControllerRoute method used in Listing 7-4 tells ASP.NET Core how to match URLs to controller classes. The configuration applied by that method declares that the Index action method defined by the Home controller will be used to handle requests.
The Contents of the Index.cshtml File in the SportsStore/Views/Home Folder
Starting the Data Model
The Contents of the Product.cs File in the SportsStore/Models Folder
The Price property has been decorated with the Column attribute to specify the SQL data type that will be used to store values for this property. Not all C# types map neatly onto SQL types, and this attribute ensures the database uses an appropriate type for the application data.
Checking and Running the Application
Running the Example Application
Adding Data to the Application
Now that the SportsStore contains some basic setup and can produce a simple response, it is time to add some data so that the application has something more useful to display. The SportsStore application will store its data in a SQL Server LocalDB database, which is accessed using Entity Framework Core. Entity Framework Core is the Microsoft object-to-relational mapping (ORM) framework, and it is the most widely used method of accessing databases in ASP.NET Core projects.
If you did not install LocalDB when you prepared your development environment in Chapter 2, you must do so now. The SportsStore application will not work without its database.
Installing the Entity Framework Core Packages
Adding the Entity Framework Core Packages to the SportsStore Project
Installing the Entity Framework Core Tool Package
Defining the Connection String
Configuration settings, such as database connection strings, are stored in JSON configuration files. To describe the connection to the database that will be used for the SportsStore data, add the entries shown in Listing 7-14 to the appsettings.json file in the SportsStore folder.
The project also contains an appsettings.Development.json file that contains configuration settings that are used only in development. This file is displayed as nested within the appsettings.json file by Solution Explorer but is always visible in Visual Studio Code. I use only the appsettings.json file for the development of the SportsStore project, but I explain the relationship between the files and how they are both used in detail in Chapter 15.
Connection strings must be expressed as a single unbroken line, which is fine in the code editor but doesn’t fit on the printed page and is the cause of the awkward formatting in Listing 7-14. When you define the connection string in your own project, make sure that the value of the SportsStoreConnection item is on a single line.
Adding a Configuration Setting in the appsettings.json File in the SportsStore Folder
This configuration string specifies a LocalDB database called SportsStore and enables the multiple active result set feature (MARS), which is required for some of the database queries that will be made by the SportsStore application using Entity Framework Core.
Pay close attention when you add the configuration setting. JSON data must be expressed exactly as shown in the listing, which means you must ensure you correctly quote the property names and values. You can download the configuration file from the GitHub repository if you have difficulty.
Each database server requires its own connection string format. A helpful site for formulating connection strings is www.connectionstrings.com.
Creating the Database Context Class
The Contents of the StoreDbContext.cs File in the SportsStore/Models Folder
The DbContext base class provides access to the Entity Framework Core’s underlying functionality, and the Products property will provide access to the Product objects in the database. The StoreDbContext class is derived from DbContext and adds the properties that will be used to read and write the application’s data. There is only one property for now, which will provide access to Product objects.
Configuring Entity Framework Core
Configuring Entity Framework Core in the Startup.cs File in the SportsStore Folder
The IConfiguration interface provides access to the ASP.NET Core configuration system, which includes the contents of the appsettings.json file and which I describe in detail in Chapter 15. The constructor receives an IConfiguration object through its constructor and assigns it to the Configuration property, which is used to access the connection string.
Entity Framework Core is configured with the AddDbContext method, which registers the database context class and configures the relationship with the database. The UseSQLServer method declares that SQL Server is being used and the connection string is read via the IConfiguration object.
Creating a Repository
The Contents of the IStoreRepository.cs File in the SportsStore/Models Folder
This interface uses IQueryable<T> to allow a caller to obtain a sequence of Product objects. The IQueryable<T> interface is derived from the more familiar IEnumerable<T> interface and represents a collection of objects that can be queried, such as those managed by a database.
A class that depends on the IProductRepository interface can obtain Product objects without needing to know the details of how they are stored or how the implementation class will deliver them.
The IQueryable<T> interface is useful because it allows a collection of objects to be queried efficiently. Later in this chapter, I add support for retrieving a subset of Product objects from a database, and using the IQueryable<T> interface allows me to ask the database for just the objects that I require using standard LINQ statements and without needing to know what database server stores the data or how it processes the query. Without the IQueryable<T> interface, I would have to retrieve all of the Product objects from the database and then discard the ones that I don’t want, which becomes an expensive operation as the amount of data used by an application increases. It is for this reason that the IQueryable<T> interface is typically used instead of IEnumerable<T> in database repository interfaces and classes.
However, care must be taken with the IQueryable<T> interface because each time the collection of objects is enumerated, the query will be evaluated again, which means that a new query will be sent to the database. This can undermine the efficiency gains of using IQueryable<T>. In such situations, you can convert the IQueryable<T> interface to a more predictable form using the ToList or ToArray extension method.
The Contents of the EFStoreRepository.cs File in the SportsStore/Models Folder
I’ll add additional functionality as I add features to the application, but for the moment, the repository implementation just maps the Products property defined by the IStoreRepository interface onto the Products property defined by the StoreDbContext class. The Products property in the context class returns a DbSet<Product> object, which implements the IQueryable<T> interface and makes it easy to implement the repository interface when using Entity Framework Core.
Earlier in the chapter, I explained that ASP.NET Core supports services that allow objects to be accessed throughout the application. One benefit of services is they allow classes to use interfaces without needing to know which implementation class is being used. I explain this in detail in Chapter 14, but for the SportsStore chapters, it means that application components can access objects that implement the IStoreRepository interface without knowing that it is the EFStoreRepository implementation class they are using. This makes it easy to change the implementation class the application uses without needing to make changes to the individual components. Add the statement shown in Listing 7-19 to the Startup class to create a service for the IStoreRepository interface that uses EFStoreRepository as the implementation class.
Don’t worry if this doesn’t make sense right now. This topic is one of the most confusing aspects of working with ASP.NET Core, and it can take a while to understand.
Creating the Repository Service in the Startup.cs File in the SportsStore Folder
The AddScoped method creates a service where each HTTP request gets its own repository object, which is the way that Entity Framework Core is typically used.
Creating the Database Migration
Entity Framework Core is able to generate the schema for the database using the data model classes through a feature called migrations. When you prepare a migration, Entity Framework Core creates a C# class that contains the SQL commands required to prepare the database. If you need to modify your model classes, then you can create a new migration that contains the SQL commands required to reflect the changes. In this way, you don’t have to worry about manually writing and testing SQL commands and can just focus on the C# model classes in the application.
Creating the Database Migration
When this command has finished, the SportsStore project will contain a Migrations folder. This is where Entity Framework Core stores its migration classes. One of the file names will be a timestamp followed by _Initial.cs, and this is the class that will be used to create the initial schema for the database. If you examine the contents of this file, you can see how the Product model class has been used to create the schema.
If you are an experienced Entity Framework developer, you may be used to using the Add-Migration command to create a database migration and to using the Update-Database command to apply it to a database.
With the introduction of .NET Core, Entity Framework Core has added commands that are integrated into the dotnet command-line tool, using the commands added by the Microsoft.EntityFrameworkCore.Tools.DotNet package. These are the commands that I have used because they are consistent with other .NET commands and they can be used in any command prompt or PowerShell window, unlike the Add-Migration and Update-Database commands, which work only in a specific Visual Studio window.
Creating Seed Data
The Contents of the SeedData.cs File in the SportsStore/Models Folder
The static EnsurePopulated method receives an IApplicationBuilder argument, which is the interface used in the Configure method of the Startup class to register middleware components to handle HTTP requests. IApplicationBuilder also provides access to the application’s services, including the Entity Framework Core database context service.
The EnsurePopulated method obtains a StoreDbContext object through the IApplicationBuilder interface and calls the Database.Migrate method if there are any pending migrations, which means that the database will be created and prepared so that it can store Product objects. Next, the number of Product objects in the database is checked. If there are no objects in the database, then the database is populated using a collection of Product objects using the AddRange method and then written to the database using the SaveChanges method.
Seeding the Database in the Startup.cs File in the SportsStore Folder
Start ASP.NET Core, and the database will be re-created and seeded with data.
Displaying a List of Products
As you have seen, the initial preparation work for an ASP.NET Core project can take some time. But the good news is that once the foundation is in place, the pace improves, and features are added more rapidly. In this section, I am going to create a controller and an action method that can display details of the products in the repository.
As I noted in Chapter 4, Visual Studio supports scaffolding to add items to a project.
I don’t use the scaffolding in this book. The code and markup that the scaffolding generates are so generic as to be all but useless, and the scenarios that are supported are narrow and don’t address common development problems. My goal in this book is not only to make sure you know how to create ASP.NET Core applications but also to explain how everything works behind the scenes, and that is harder to do when responsibility for creating components is handed to the scaffolding.
If you are using Visual Scer in the Solution Explorer, selecting Add ➤ New Item from the pop-up menu, and then choosing an item template from the Add New Item window.
You may find your development style to be different from mine, and you may find that you prefer working with the scaffolding in your own projects. That’s perfectly reasonable, although I recommend you take the time to understand what the scaffolding does so you know where to look if you don’t get the results you expect.
Preparing the Controller
Preparing the Controller in the HomeController.cs File in the SportsStore/Controllers Folder
When ASP.NET Core needs to create a new instance of the HomeController class to handle an HTTP request, it will inspect the constructor and see that it requires an object that implements the IStoreRepository interface. To determine what implementation class should be used, ASP.NET Core consults the configuration in the Startup class, which tells it that EFStoreRepository should be used and that a new instance should be created for every request. ASP.NET Core creates a new EFStoreRepository object and uses it to invoke the HomeController constructor to create the controller object that will process the HTTP request.
This is known as dependency injection, and its approach allows the HomeController object to access the application’s repository through the IStoreRepository interface without knowing which implementation class has been configured. I could reconfigure the service to use a different implementation class—one that doesn’t use Entity Framework Core, for example—and dependency injection means that the controller will continue to work without changes.
Some developers don’t like dependency injection and believe it makes applications more complicated. That’s not my view, but if you are new to dependency injection, then I recommend you wait until you have read Chapter 14 before you make up your mind.
It is a little awkward to get the data returned from the action method. The result is a ViewResult object, and I have to cast the value of its ViewData.Model property to the expected data type. I explain the different result types that can be returned by action methods and how to work with them in Part 2.
Updating the View
Using the Product Data in the Index.cshtml File in the SportsStore/Views/Home Folder
The @model expression at the top of the file specifies that the view expects to receive a sequence of Product objects from the action method as its model data. I use an @foreach expression to work through the sequence and generate a simple set of HTML elements for each Product object that is received.
The view doesn’t know where the Product objects came from, how they were obtained, or whether they represent all the products known to the application. Instead, the view deals only with how details of each Product are displayed using HTML elements.
I converted the Price property to a string using the ToString("c") method, which renders numerical values as currency according to the culture settings that are in effect on your server. For example, if the server is set up as en-US, then (1002.3).ToString("c") will return $1,002.30, but if the server is set to en-GB, then the same method will return £1,002.30.
Running the Application
Adding Pagination
Adding Pagination in the HomeController.cs File in the SportsStore/Controllers Folder
The PageSize field specifies that I want four products per page. I have added an optional parameter to the Index method, which means that if the method is called without a parameter, the call is treated as though I had supplied the value specified in the parameter definition, with the effect that the action method displays the first page of products when it is invoked without an argument. Within the body of the action method, I get the Product objects, order them by the primary key, skip over the products that occur before the start of the current page, and take the number of products specified by the PageSize field.
You can see the new test follows the pattern of the existing one, relying on Moq to provide a known set of data with which to work.
Displaying Page Links
Using these query strings, you can navigate through the catalog of products. There is no way for customers to figure out that these query string parameters exist, and even if there were, customers are not going to want to navigate this way. Instead, I need to render some page links at the bottom of each list of products so that customers can navigate between pages. To do this, I am going to create a tag helper, which generates the HTML markup for the links I require.
Adding the View Model
The Contents of the PagingInfo.cs File in the SportsStore/Models/ViewModels Folder
Adding the Tag Helper Class
Now that I have a view model, it is time to create a tag helper class. Create a folder named Infrastructure in the SportsStore project and add to it a class file called PageLinkTagHelper.cs, with the code shown in Listing 7-27. Tag helpers are a big part of ASP.NET Core development, and I explain how they work and how to use and create them in Chapters 25–27.
The Infrastructure folder is where I put classes that deliver the plumbing for an application but that are not related to the application’s main functionality. You don’t have to follow this convention in your own projects.
The Contents of the PageLinkTagHelper.cs File in the SportsStore/Infrastructure Folder
This tag helper populates a div element with a elements that correspond to pages of products. I am not going to go into detail about tag helpers now; it is enough to know that they are one of the most useful ways that you can introduce C# logic into your views. The code for a tag helper can look tortured because C# and HTML don’t mix easily. But using tag helpers is preferable to including blocks of C# code in a view because a tag helper can be easily unit tested.
Registering a Tag Helper in the _ViewImports.cshtml File in the SportsStore/Views Folder
The complexity in this test is in creating the objects that are required to create and use a tag helper. Tag helpers use IUrlHelperFactory objects to generate URLs that target different parts of the application, and I have used Moq to create an implementation of this interface and the related IUrlHelper interface that provides test data.
The core part of the test verifies the tag helper output by using a literal string value that contains double quotes. C# is perfectly capable of working with such strings, as long as the string is prefixed with @ and uses two sets of double quotes ("") in place of one set of double quotes. You must remember not to break the literal string into separate lines unless the string you are comparing to is similarly broken. For example, the literal I use in the test method has wrapped onto several lines because the width of a printed page is narrow. I have not added a newline character; if I did, the test would fail.
Adding the View Model Data
The Contents of the ProductsListViewModel.cs File in the SportsStore/Models/ViewModels Folder
Updating the Action Method in the HomeController.cs File in the SportsStore/Controllers Folder
These changes pass a ProductsListViewModel object as the model data to the view.
I would usually create a common setup method, given the degree of duplication between these two test methods. However, since I am delivering the unit tests in individual sidebars like this one, I am going to keep everything separate so you can see each test on its own.
Updating the Index.cshtml File in the SportsStore/Views/Home Folder
I have changed the @model directive to tell Razor that I am now working with a different data type. I updated the foreach loop so that the data source is the Products property of the model data.
Displaying the Page Links
Adding the Pagination Links in the Index.cshtml File in the SportsStore/Views/Home Folder
Improving the URLs
Adding a New Route in the Startup.cs File in the SportsStore Folder
It is important that you add the new route before the call to the MapDefaultControllerRoute method. As you will learn in Chapter 13, the routing system processes routes in the order they are listed, and I need the new route to take precedence over the existing one.
This is the only alteration required to change the URL scheme for product pagination. ASP.NET Core and the routing function are tightly integrated, so the application automatically reflects a change like this in the URLs used by the application, including those generated by tag helpers like the one I use to generate the page navigation links.
Styling the Content
Installing the Bootstrap Package
Installing the LibMan Tool Package
Initializing the Example Project
Applying Bootstrap Styles
Applying Bootstrap CSS to the _Layout.cshtml File in the SportsStore/Views/Shared Folder
Styling Content in the Index.cshtml File in the SportsStore/Views/HomeFolder
Adding Classes to Elements in the PageLinkTagHelper.cs File in the SportsStore/Infrastructure Folder
The values of the attributes are automatically used to set the tag helper property values, with the mapping between the HTML attribute name format (page-class-normal) and the C# property name format (PageClassNormal) taken into account. This allows tag helpers to respond differently based on the attributes of an HTML element, creating a more flexible way to generate content in an ASP.NET Core application.
Creating a Partial View
The Contents of the ProductSummary.cshtml File in the SportsStore/Views/Shared Folder
Using a Partial View in the Index.cshtml File in the SportsStore/Views/Home Folder
I have taken the markup that was previously in the @foreach expression in the Index.cshtml view and moved it to the new partial view. I call the partial view using a partial element, using the name and model attributes to specify the name of the partial view and its view model. Using a partial view allows the same markup to be inserted into any view that needs to display a summary of a product.
Restart ASP.NET Core and request http://localhost:5000, and you will see that introducing the partial view doesn’t change the appearance of the application; it just changes where Razor finds the content that is used to generate the response sent to the browser.
Summary
In this chapter, I built the core infrastructure for the SportsStore application. It does not have many features that you could demonstrate to a client at this point, but behind the scenes, there are the beginnings of a domain model with a product repository backed by SQL Server and Entity Framework Core. There is a single controller, HomeController, that can produce paginated lists of products, and I have set up a clean and friendly URL scheme.
If this chapter felt like a lot of setup for little benefit, then the next chapter will balance the equation. Now that the fundamental structure is in place, we can forge ahead and add all the customer-facing features: navigation by category and the start of a shopping cart.