By the end of this book you will be able to create simple ASP.NET Core MVC applications on your own, which can create, edit, delete, and view data in a database.. Your First ASP.NET Core
Trang 1ASP.NET Core 1.1 MVC
For Beginners How to build a Video Course Website
Trang 2Overview 1
Setup 2
Other Titles by the Author 2
MVC 5 – How to Build a Membership Website (video course) 2
Store Secret Data in NET Core Web App with Azure Key Vault (video course) 3
C# for Beginners: The Tactical Guidebook 3
ASP.NET MVC 5 – Building a Website: The Tactical Guidebook 4
Source Code and Bonus Materials 5
Disclaimer – Who Is This Book for? 5
Rights 5
About the Author 6
Part 1: ASP.NET Core 1.1 MVC Your First Application 7
1 Your First ASP.NET Core Application 8
Creating the Solution and Project 8
The Project Layout and the File System 11
Important Files 12
Compiling the Solution 13
The Startup.cs File 14
Adding a Configuration Service 15
Creating a Service 18
Example 18
Adding the Interface 19
Adding the HardcodedMessageService Class 20
Configure and Use the HardcodedMessageService Class 20
Add and Use the ConfigurationMessageService Class 22
Summary 24
Trang 32 Middleware 25
How Does Middleware Work? 25
IApplicationBuilder 26
Handling Exceptions 28
Serving Up Static Files 31
Serving Up Default Files 33
Setting Up ASP.NET MVC 33
Adding the MVC NuGet Package 34
Summary 36
3 MVC Controllers 37
Routing 38
Convention-Based Routing 39
Implement Routing 40
Adding Another Controller 42
Attribute Routing 43
IActionResult 46
Implementing ContentResult 47
Using a Model Class 47
Introduction to Views 49
A View with a Data Collection 50
Adding a Data Service 53
Summary 57
4 Models 58
View Model Example 59
Changing the Folder Structure 59
Adding the View Model 59
Using the View Model 60
Trang 4Adding a Details View 61
Adding a Create View 65
Refactoring the Application 66
Adding the HTTP GET Create Action and the Create View 68
Adding the VideoEditViewModel Class 70
Adding the HTTP POST Create Action 71
Data Annotations 76
Preparing the Crate View for Validation 77
Adding Validation to the Create View 77
Validating the Model on the Server 78
Adding Data Annotations in the Video Entity and the VideoEditViewModel Class 79
Summary 82
5 Entity Framework 83
Installing Entity Framework and User Secrets 83
Adding the VideoDbContext Class 85
Configuration in the Startup Class 86
Adding the Initial Migration and Creating the Database 88
Adding the SqlVideoData Service Component 90
Implementing the SqlVideoData Service Component Class 90
Summary 93
6 Razor Views 94
Layout Views 94
Adding the _Layout View 95
Altering the Content Views 95
The _ViewStart file 99
The _ViewImports file 100
Tag Helpers 101
Trang 5Altering the Index View 102
Adding an Edit View and Its Actions 103
Refactoring the IVideoData Service 106
Partial Views 109
View Components 112
Adding a View Component for the IMessageService Service 112
Summary 115
7 Forms Authentication 116
Adding the Authorize and AlowAnonymous Attributes 117
Configuring the Identity Framework 118
Creating the AspNet Identity Database Tables 120
User Registration 121
Login and Logout 126
Adding the _Login Partial View 126
Adding the Logout Action 128
Adding the LoginViewModel Class 129
Adding the HTTP GET Login Action 130
Adding the HTTP POST Login Action 131
Adding the Login View 133
Summary 135
8 Front-End Frameworks 137
Installing Bower and the Frameworks 137
Styling with Bootstrap 140
Adding a Navigation Bar 141
Styling the Index View 143
Adding Client-Side Validation 145
Summary 147
Trang 6Part 2: ASP.NET Core 1.1 MVC How to Build a Video Course Website 148
9 The Use Case 149
Introduction 149
The Use Case 149
The User Interface 149
Login and Register User 150
The Administrator Views 150
Conclusion 151
Login and Register 151
The Dashboard View 151
The Course View 152
The Video View 154
A Typical Administrator Index View 155
A Typical Administrator Create View 155
A Typical Administrator Edit View 156
A Typical Administrator Delete View 157
A Typical Administrator Details View 158
10 Setting Up the Solution 159
Introduction 159
Technologies Used in This Chapter 159
Overview 159
Creating the Solution 159
Installing AutoMapper 161
Summary 162
11 Login 163
Introduction 163
Technologies Used in This Chapter 163
Trang 7Creating the Database 163
Redirecting to the Login View 165
Styling the Login View 167
Adding the login.css Stylesheet 168
Changing the Layout of the View 169
Styling the Login View 173
Summary 175
12 Register User 176
Introduction 176
Technologies Used in This Chapter 176
Overview 176
Changing the Layout of the View 177
Styling the Register View 179
Testing the Registration Form 181
Summary 183
13 Modifying the Navigation Bar 184
Introduction 184
Technologies Used in This Chapter 184
Overview 184
Styling the Navigation Bar 185
Remove the Register and Login links 186
Add the Drop-Down Menu 187
Style the Drop-Down Menu 189
Summary 190
14 Data Transfer Objects 191
Introduction 191
Technologies Used in This Chapter 191
Trang 8Overview 191
The DTOs 191
Adding the DTOs 196
The View Models 199
Adding the View Models 200
Summary 201
15 Entity Classes 202
Introduction 202
Technologies Used in This Chapter 202
Overview 202
The Entities 202
The Video Entity 202
The Download Entity 203
The Instructor Entity 204
The Course Entity 204
The Module Entity 205
The UserCourse Entity 205
Adding the Entity Classes 206
Summary 209
16 Mock Data Repository 210
Introduction 210
Technologies Used in This Chapter 210
Overview 210
Add the IReadRepository Interface and MockReadRepository Class 210
Add Data to the MockReadRepository Class 211
The Course List 211
The UserCourses List 212
Trang 9The Modules List 212
The Downloads List 212
The Instructors List 213
The Videos List 213
The GetCourses Method 214
Testing the GetCourses Method 215
The GetCourse Method 215
Testing the GetCourse Method 217
The GetVideo Method 218
Testing the GetVideo Method 218
The GetVideos Method 219
Testing the GetVideos Method 220
Summary 223
17 The Membership Controller and AutoMapper 224
Introduction 224
Technologies Used in This Chapter 224
Overview 224
Adding the Membership Controller 225
Adding the Controller 225
Configuring AutoMapper 228
Implementing the Action Methods 230
The Dashboard Action Method 230
The Course Action Method 234
The Video Action Method 238
Summary 243
18 The Dashboard View 244
Introduction 244
Trang 10Technologies Used in This Chapter 244
Overview 244
Implementing the Dashboard View 245
Adding the Dashboard View 245
Iterating Over the Courses in the Dashboard View 247
Creating the _CoursePanelPartial Partial View 250
Styling the Dashboard View and the _CoursePanelPartial Partial View 252
Summary 256
19 The Course View 257
Introduction 257
Technologies Used in This Chapter 257
Overview 257
Adding the Course View 258
Adding the Back to Dashboard Button 260
Adding the Course.css Style Sheet 262
Adding the Course Information to the View 262
Styling the Course Information Section 265
Adding Columns for the Modules and the Instructor Bio 266
Adding the Modules 267
Adding the Videos 268
Styling the _ModuleVideosPartial View 272
Adding the Downloads 274
Styling the _ModuleDownloadsPartial View 277
Adding the Instructor Bio 278
Styling the _InstructorBioPartial Partial View 280
Summary 280
20 The Video View 281
Trang 11Introduction 281
Technologies Used in This Chapter 281
Overview 281
Adding the Video View 283
Adding the Back to Course Button 285
Adding Row and Columns for the Video View Content 286
Adding the _VideoPlayerPartial Partial View 287
Styling the _VideoPlayerPartial Partial View 290
Add JWPlayer 291
Create a Video Player 292
Add the Video Player to the Video View 292
Adding Properties to the LessonInfoDTO Class 293
Adding the _VideoComingUpPartial Partial View 294
Styling the _VideoComingUpPartial Partial View 299
Adding the _InstructorBioPartial Partial View 299
Summary 301
21 SQL Data Repository 302
Introduction 302
Technologies used in this chapter 302
Overview 302
Adding the Tables 303
Adding the Entity Classes to the ApplicationDbContext 303
Adding Seed Data 305
Creating the Tables 310
Adding the SqlReadRepository 312
Implementing the GetCourses method 312
Implementing the GetCourse Method 314
Trang 12Implementing the GetVideo Method 316
Implementing the GetVideos Method 316
Summary 317
22 The Admin Menu 318
Introduction 318
Technologies Used in This Chapter 318
Overview 318
Adding the _AdminMenuPartial Partial View 319
Summary 322
23 Controllers and Views 323
Introduction 323
Technologies used in this chapter 323
Overview 323
Adding Controllers and Views 327
Fixing the Drop-Downs in the Views 330
The Index Action 334
The Index View 335
The Details Action 336
The Details View 337
The HTTP GET Delete Action 338
The HTTP POST DeleteConfirmed Action 338
The Delete View 338
The HTTP GET Create Action 339
The HTTP POST Create Action 339
The Create View 340
The HTTP GET Edit Action 343
The HTTP POST Edit Action 343
Trang 13The Edit View 345
Summary 345
24 The UserCourse Controller 346
Technologies used in this chapter 346
Overview 346
The UserCourse Controller 346
Creating the UserCoursesController Class 347
Adding the Index Action and View 348
Adding the Details Action and View 352
Adding the HTTP GET Create Action and View 356
Adding the HTTP POST Create Action 359
Adding the HTTP GET Edit Action and View 361
Adding the HTTP POST Edit Action 364
Adding the HTTP GET Delete Action and View 368
Adding the HTTP POST DeleteConfirmed Action 370
Authorize and Route Attributes in the Admin Controllers 372
Changing the Route and Adding Authorization 372
Summary 373
25 Custom Tag Helper 374
Introduction 374
Technologies Used in This Chapter 374
Overview 375
Implementing the Button-Container Tag Helper 375
Creating the Tag Helper 376
Multiple Actions and Descriptions 379
URL Parameter Values 381
Glyphicons 384
Trang 14Turning Links into Buttons 386
Styling the Views 386
Replacing Links with Buttons 389
An Alternate Button-Container Tag Helper 391
Summary 394
Other Titles by the Author 395
Video Courses 395
MVC 5 – How to Build a Membership Website (video course) 395
Store Secret Data in a NET Core Web App with Azure Key Vault (video course) 395
Books 396
ASP.NET MVC 5 – Building a Website: The Tactical Guidebook 396
C# for Beginners: The Tactical Guidebook 397
Trang 15Overview
I would like to welcome you to ASP.NET Core 1.1 MVC for Beginners This book will guide
you through creating your very first MVC applications To get the most from this book, you should have a basic understanding of HTML and be familiar with the C# language
ASP.NET Core is a new framework from Microsoft It has been designed from the ground
up to be fast and flexible and to work across multiple platforms ASP.NET Core is the framework to use for your future ASP.NET applications
The first application you build will evolve into a basic MVC application, starting with an empty template You will add the necessary pieces one at a time to get a good under-standing of how things fit together The focus is on installing and configuring middleware, services, and other frameworks Styling with CSS is not a priority in this application; you’ll learn more about that in the second application you build
You will install middleware to create a processing pipeline, and then look at the MVC framework If you already are familiar with MVC or Web API from previous versions of ASP.NET, you will notice some similarities
There still are model classes, which are used as data carriers between the controller and its views There are, however, many new features that you will learn, such as Tag Helpers and view components You will also work with Entity Framework to store and retrieve data, implement authentication with ASP.NET Identity framework, install CSS libraries such as Bootstrap, and install JavaScript libraries such as JQuery Note that dependency injection now is a first-class design pattern
The second application you will create, starts from a pre-existing MVC template, where the main pipeline already has been added Things like database support, authentication, and routing have already been implemented, ready to use
By the end of this book you will be able to create simple ASP.NET Core MVC applications
on your own, which can create, edit, delete, and view data in a database
Both applications you will build revolve around video data and playing videos In the first application, you will be able to add and edit video titles, and in the second you will build a more sophisticated customer portal, where users can view the course videos that they have access to
Trang 16Setup
In this book, you will be using C# and any Visual Studio 2017 version that you have access
to You can even use the free Visual Studio Community 2017 version, which you can load from www.visualstudio.com/downloads
down-You can develop ASP.NET Core applications on Mac OS X and Linux, but then you are restricted to the ASP.NET Core libraries that don’t depend on NET Framework, which requires Windows
The applications in this book require ASP.NET 1.1 with NET Framework, which mean that you must develop on a Windows machine, or a virtual machine with Windows installed You will install additional libraries using NuGet packages when necessary, throughout the book
The complete code for both applications is available on GitHub with a commit for each task
The first application: https://github.com/csharpschool/AspNetCoreVideo
The second application: https://github.com/csharpschool/VideoOnDemand
Other Titles by the Author
The author has written other books and produced video courses that you might find helpful
MVC 5 – How to Build a Membership Website (video course)
This is a comprehensive video course on how to build a membership site using ASP.NET
MVC 5 The course has more than 24 hours of video
Trang 17In this video course you will learn how to build a membership website from scratch You will create the database using Entity Framework code-first, scaffold an Administrator UI, and build a front-end UI using HTML5, CSS3, Bootstrap, JavaScript, C#, and MVC 5 Prereq-uisites for this course are: a good knowledge of the C# language and basic knowledge of MVC 5, HTML5, CSS3, Bootstrap, and JavaScript
You can watch this video course on Udemy at this URL:
www.udemy.com/building-a-mvc-5-membership-website
Store Secret Data in NET Core Web App with Azure Key Vault (video course)
In this Udemy course you will learn how to store sensitive data in a secure manner First
you will learn how to store data securely in a file called secrets.json with the User Manager
The file is stored locally on your machine, outside the project’s folder structure It is therefore not checked into your code repository Then you will learn how to use Azure Web App Settings to store key-value pairs for a specific web application The third and final way to secure your sensitive data is using Azure Key Vault, secured with Azure Active Directory in the cloud
The course is taught using a ASP.NET Core 1.1 Web API solution in Visual Studio 2015 You really need to know this if you are a serious developer
You can watch this video course on Udemy at this URL:
www.udemy.com/store-secret-data-in-net-core-web-app-with-azure-key-vault
C# for Beginners: The Tactical Guidebook
This book is for YOU if you are new to C# or want to brush up on your skills, and like a CHALLENGE This is not your run-of-the-mill encyclopedic programming book; it is highly
modularized, tactical, and practical – meaning that you learn by reading theory, and then implement targeted exercises building many applications
Trang 18You can buy C# for Beginners: The Tactical Guidebook on Amazon at this URL:
https://www.amazon.com/dp/B017OAFR8I
ASP.NET MVC 5 – Building a Website: The Tactical Guidebook
This book is primarily aimed at developers who have some prior experience with MVC 5 and are proficient in C#, since the language won’t be explained in any detail Even if you already have created a couple of MVC projects, you might find the content in this book useful as a refresher You might have worked in previous versions of Visual Studio and MVC and want a fast, no-fluff way to get up to speed with MVC 5
You can buy ASP.NET MVC 5 – Building a Website: The Tactical Guidebook on Amazon at
this URL: www.amazon.com/dp/B01IF63FIY
Trang 19Source Code and Bonus Materials
The source code accompanying this book is shared under the MIT License and can be downloaded on GitHub, with a commit for each task
The first application: https://github.com/csharpschool/AspNetCoreVideo
The second application: https://github.com/csharpschool/VideoOnDemand
Disclaimer – Who Is This Book for?
It’s important to mention that this book is not meant to be a get-to-know-it-all book; it's
more on the practical and tactical side, where you will learn as you progress through the exercises and build real applications in the process Because I personally dislike having to read hundreds upon hundreds of pages of irrelevant fluff (filler material) not necessary for the tasks at hand, and also view it as a disservice to the readers, I will assume that we are
of the same mind on this, and will therefore only include important information pertinent for the tasks at hand, thus making the book both shorter and more condensed and also saving you time and effort in the process Don't get me wrong, I will describe the important things in great detail, leaving out only the things that are not directly relevant to your first experience with a ASP.NET Core 1.1 MVC Web Application The goal is for you to have created a working MVC application upon finishing this book You can always look into
details at a later time when you have a few projects under your belt If you prefer
encyclopedic books describing everything in minute detail with short examples, and value a book by how many pages it has, rather than its content, then this book is NOT for you
The examples in this book are presented using the free Visual Studio 2017 Community version and ASP.NET Core 1.1 You can download Visual Studio 2017 here:
www.visualstudio.com/downloads
Rights
All rights reserved The content is presented as is and the publisher and author assume no responsibility for errors or omissions Nor is any liability assumed for damages resulting from the use of the information in the book or the accompanying source code
It is strictly prohibited to reproduce or transmit the whole book, or any part of the book,
in any form or by any means without the prior written permission of the author
Trang 20You can reach the author at: info@csharpschool.com
ISBN-13: , ISBN-10:
Copyright © 2017 by Jonas Fagerberg, All rights reserved
About the Author
Jonas started a company back in 1994 focusing on teaching Microsoft Office and the Microsoft operating systems While still studying at the university of Skovde in 1995, he wrote his first book about Widows 95, as well as a number of course materials
In the year 2000, after working as a Microsoft Office developer consultant for a couple of years, he wrote his second book about Visual Basic 6.0
Between 2000 and 2004, he worked as a Microsoft instructor with two of the largest educational companies in Sweden teaching Visual Basic 6.0 When Visual Basic.NET and C# were released, he started teaching those languages, as well as the NET Framework He was also involved in teaching classes at all levels, from beginner to advanced developers From the year 2005, Jonas shifted his career towards consulting once again, working hands-on with the languages and framework he taught
Jonas wrote his third book, C# Programming, aimed at beginner to intermediate
develop-ers in 2013, and in 2015 his fourth book C# for Beginners – The Tactical Guide was
published Shortly thereafter his fifth book, ASP.NET MVC 5 – Building a Website: The Tactical Guidebook, was published
Jonas has also produced a 24h+ video course titled Building a ASP.NET MVC 5 Membership
Website (www.udemy.com/building-a-mvc-5-membership-website), showing in great
detail how to build a membership website
And a course on how to secure sensitive data in web applications titled Store Secret Data
in a NET Core Web App with Azure Key Vault is also available on Udemy
All the books and video courses, including C# for Beginners – The Tactical Guide, MVC 5 – How to Build a Membership Website (book and video), Store Secret Data in a NET Core Web App with Azure Key Vault, and this book, have been specifically written with the
student in mind
Trang 21Part 1:
ASP.NET Core 1.1 MVC Your First Application
Trang 221 Your First ASP.NET Core Application Now that you have Visual Studio 2017 installed on your computer, it’s time to create your first project
Creating the Solution and Project
1 Open Visual Studio 2017
2 Select File-New-Project (Ctrl+Shift+N) in the main menu
3 Make sure that the Templates-Visual C#-Web node is selected in the New Project dialog
There are three templates available:
a ASP.NET Web Application (.NET Framework)
Can be used to create traditional ASP.NET web applications (without NET Core)
b ASP.NET Core Web Application (.NET Core)
Can be used to create cross-platform ASP.NET Core web applications without the NET Framework (not restricted to Windows)
c ASP.NET Core Web Application (.NET Framework)
Can be used to create ASP.NET Core web applications dependent on NET Framework (not cross-platform)
4 Select the ASP.NET Core Web Application (.NET Framework) template
5 Give the application a name and select which folder to place it in You can name
it AspNetCoreVideo
6 Make sure that the Create directory for solution checkbox is checked
7 Learning how to use GitHub is not part of this course, so if you are unfamiliar
with GitHub, you should make sure that the Create new Git repository checkbox
is unchecked
8 Click the OK button
Trang 239 In the next dialog, make sure that the ASP.NET Core 1.1 framework is selected at
the top left of the dialog
10 Select the Empty template
11 Click the OK button
12 When the solution has been created in the folder you selected, it will contain all
the files in the AspNetCoreVideo project
13 Press Ctrl+F5 on the keyboard, or select Debug-Start Without Debugging in the
main menu, to run the application in the browser
14 Note that the application only can do one thing right now, and that is to display
the text Hello World! Later in this, and the next, module you will learn why that
is, and how you can change that behavior
Trang 24For now, just note that the application is running on localhost:51457 (the port number
might be different on your machine)
If you right click on the IIS icon in the system tray, you can see that ISS is hosting the
AspNetCoreVideo application
Trang 25The Project Layout and the File System
There is a direct correlation between the files in the solution folder and what is displayed
in the Solution Explorer in Visual Studio To demonstrate this, you will add a file to the file structure in the File Explorer and see it show up in the Solution Explorer in real-time
1 Right click on the Solution node in the Solution Explorer and select Open Folder
in File Explorer
2 When the File Explorer has opened, you can see that the solution file
AspNetCoreVideo.sln is in that folder, along with the project folder with the same
name
3 Double click on the project folder in the File Explorer to open it
4 Right click in the File Explorer window and select New-Text Document and press Enter on the keyboard
5 A new file with the name New Text File should have been created in the folder
6 Now look in the Solution Explorer in Visual Studio; the same file should be available there
7 Double click the icon for the New Text File document in the Solution Explorer in
Visual Studio, to open it
8 Write the text Some text from Visual Studio in the document and save it
9 Now switch back to the File Explorer and open the file It should contain the text you added
10 Change the text to Some text from Notepad using the text editor (not in Visual
Studio) and save the file
11 Switch back to Visual Studio and click the Yes button in the dialog The altered
text should now be displayed in Visual Studio
12 Close the text document in Visual Studio and in the text editor
Trang 2613 Right click on the file in the Solution Explorer in Visual Studio and select Delete
to remove the file permanently
14 Go to the File Explorer and verify that the file was deleted from the folder
The Properties folder in the Solution Explorer contains a file called launchSettings.json,
which contains all the settings needed to launch the application It contains IIS settings, as well as project settings, such as environment variables and the application URL
One major change from ASP.NET Core 1.0 is that the project.json file no longer exists;
instead the installed NuGet packages are listed in the csproj file It can be opened and
edited directly from Visual Studio (which is another change) or its content can be changed using the NuGet Package Manager
To open the csproj file, you simply right click on it and select Edit AspNetCoreVideo.csproj
(substitute AspNetCoreVideo with the name of the project you are in)
You can add NuGet packages by adding PackageReference nodes to the file csproj, or by
opening the NuGet Package Manager Right click on the project node or the References node, and select Manage NuGet Packages to open the NuGet Manager
Open the csproj file and the NuGet manager side by side and compare them As you can
see, the same packages are listed in the dialog and in the file
Trang 27You will be adding more NuGet packages (frameworks) as you build the projects
Compiling the Solution
It is important to know that ASP.NET will monitor the file system and recompile the cation when files are changed and saved Because ASP.NET monitors the file system and recompiles the code, you can use any text editor you like, such as Visual Studio Code, when building your applications You are no longer bound to Visual Studio; all you need to do is
appli-to get the application running in the web server (IIS) Let’s illustrate it with an example
1 Start the application without debugging (Ctrl+F5) to get it running in IIS, if it isn’t already open in a browser
2 Open the Startup.cs file with Notepad (or any text editor) outside of Visual
Studio This file is responsible for configuring your application when it starts
3 Locate the line of code with the string Hello World This line of code is
responsible for responding to every HTTP request in your application
await context.Response.WriteAsync( "Hello World!" );
4 Change the text to Hello, from My World! and save the file
await context.Response.WriteAsync( "Hello, from My World!" );
Trang 285 Refresh the application in the browser Do not build the solution in Visual Studio before refreshing the page
6 The text should change from Hello World! To Hello, from My World!
The reason this works is because ASP.NET monitors the file system and
recompiles the application when changes are made to a file
As mentioned earlier you can create cross-platform applications using ASP.NET Core 1.1,
but this requires the NET Core template As of this writing, this template has limitations compared with the NET Framework template This, because NET Framework contains
features that are relying on the Windows operating system In a few years’ time, this gap will probably not be as significant, as the NET Core platform evolves So, if you don’t need
the added features in NET Framework, then use the NET Core template, as it is much
leaner and cross-platform ready
The Startup.cs File
Gone are the days when the web.config file ruled the configuration universe Now the
Startup.cs file contains a Startup class, which ASP.NET will look for by convention The
application and its configuration sources are configured in that class
The Configure and ConfigureServices methods in the Startup class handle most of the application configuration The HTTP processing pipeline is created in the Configure
method, located at the end of the class The pipeline defines how the application responds
to requests; by default, the only thing it can do is to print Hello World! to the browser
If you want to change this behavior, you will have to add additional code to the pipeline
in this method If you for instance want to serve up static files, like HTML or JSON, you will need to add that behavior to the pipeline
If you want to add a pretty error page, or handle route request in an ASP.NET MVC cation, you have to modify the pipeline
Trang 29appli-The Configure method is where you set up the application’s inversion of control container,
which will be covered more in the second part of this book
The second method in the Startup class is ConfigureServices, which is used to configure
the application services
You will learn more about how to configure your application in the next chapter
For now, all you need to know about dependency injection is that, instead of creating stances of a class explicitly, they can be handed to a component when asked for This makes your application loosely coupled and flexible
in-Adding a Configuration Service
Let’s say that the hard-coded string Hello, from My World is a string that shouldn’t be
hardcoded, and you want to read it from a configuration source The source is irrelevant;
it could be a JSON file, a database, a web service, or some other source To solve this, you could implement a configuration service that fetches the value when asked
Let’s implement this scenario in your application
1 Right click on the project folder and select Add-New Item
2 Search for JSON in the dialog’s search field
3 Select the ASP.NET Configuration File template
4 Make sure the name of the file is appsettings.json The file could be named anything, but appsettings is convention for this type of configuration file
5 Click the Add button
6 As you can see, a default connection string is already in the file Remove the connection string property and add the following key-value pair:
“Message”:”Hello, from configuration” This is the file content after you have
changed it
{
"Message" : "Hello, from configuration"
}
7 To read configuration information from the appsettings.json file you have to add
a constructor to the Startup class You can do that by typing ctor and hitting the
Tab key twice
public class Startup
{
Trang 30current directory as an argument Without specifying the base path, the
application will not know where to search for files
var builder = new ConfigurationBuilder ()
.SetBasePath( Directory GetCurrentDirectory());
9 To read the JSON appsettings.json file you need to chain on the AddJsonFile method, with appsettings.json as an argument, to the builder object If you need
to include more files, you can chain on the method multiple times
var builder = new ConfigurationBuilder ()
.SetBasePath( Directory GetCurrentDirectory())
.AddJsonFile( "appsettings.json");
10 Add a property called Configuration, of type IConfiguration, to the Startup class
To get access to the interface you have to add a using statement to the
Microsoft.Extensions.Configuration namespace
public IConfiguration Configuration { get ; set ; }
11 Now, you need to build the configuration structure from the
ConfigurationBuilder object, and store it in the Configuration property You do this by calling the Build method on the builder variable in the constructor
Configuration = builder.Build();
12 To replace the hardcoded text Hello, from My World! With the value stored in
the Message property in the appsettings.json file, you have to index into the
Configuration property Store the value in a variable in the Configure method
var message = Configuration[ "Message" ];
13 Now, replace the hardcoded text with the variable
await context.Response.WriteAsync(message);
14 Save all the files and go to the browser Refresh the application to see the new message
Trang 31The Startup class’ code, so far:
public class Startup
{
public IConfiguration Configuration { get ; set ; }
public Startup()
{
var builder = new ConfigurationBuilder ()
SetBasePath( Directory GetCurrentDirectory()) .AddJsonFile( "appsettings.json" );
Configuration = builder.Build();
}
public void Configure( IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory) {
Trang 32Creating a Service
Instead of using one specific source to fetch data, you can use services to fetch data from different sources, depending on the circumstance This mean that you, through the use of configuration, can use different data sources according to the need at hand
You might want to fetch data from a JSON file when building the service, and later switch
to another implementation of that service, to fetch real data
To achieve this, you create an interface that the service classes implement, and then use that interface when serving up the instances Because the service classes implement the same interface, instances from them are interchangeable
To get access to the services from the Configure method in the Startup class, or any other
constructor, model, or view, you must use dependency injection That is, pass in the interface as a parameter to the method
You must register the service interface, and the desired service class, with the services collection in the ConfgureServices method, in the Startup class This determines which
class will be used to create the instance, when dependency injection is used to pass in an instance of a class implementing the interface
In the upcoming example, you will inject a service class into the Configure method, but it
works just as well with regular classes that you want to inject into a constructor, model,
or view, using dependency injection The same type of registration that you did in the
ConfigureServices method could be applied to this scenario, but you wouldn’t have to
implement it as a service
You might ask how the IApplicationBuilder parameter gets populated in the Configure method, when no configuration has been added for it in the ConfigureServices method
The answer is that certain service objects will be served up for interfaces automatically by
ASP.NET; one of those interfaces is the IApplicationBuilder Another is the Environment service, which handles different environments, such as development,
IHosting-staging, and production
Example
Let’s implement an example where you create two service classes that retrieve data in two different ways The first will simply return a hardcoded string (you can pretend that the
Trang 33data is fetched from a database or a web service if you like), and the second class will
return the value from the Message property that you added to the appsettings.json file
You will begin by adding an interface called IMessage service, which will define a method called GetMessage, which returns a string
Then you will implement that interface in a service class called Service, which will return a hardcoded string After implementing the class, you will add configuration for it and the interface in the ConfigureServices method and test the
HardcodedMessage-functionality
Then you will implement another class called ConfigurationMessageService, which reads
from the application.json file and returns the value from the Message property To use
the new service class, you must change the configuration Then you will refresh the cation in the browser to make sure that the configuration value is returned
appli-Adding the Interface
1 Right click on the project node in the Solution Explorer and select Add-New Folder
2 Name the folder Services
3 Right click on the Services folder and select Add-New Item
4 Select the Interface template, name the interface IMessageService, and click the Add button
5 Add the public access modifier to the interface (make it public)
6 Add a method called GetMessage, which return a string to the interface It
should not take any parameters
7 Save the file
The complete code for the interface:
public interface IMessageService
{
string GetMessage();
}
Trang 34Adding the HardcodedMessageService Class
1 Right click on the Services folder and select Add-Class
2 Name the class HardcodedMessageService and click the Add button
3 Implement the IMessageService interface in the class by clicking on the lightbulb
icon that appears when you hover over the interface name when you have
added it to the class Select Implement interface in the menu that appears
4 Remove the code line with the throw statement and return the string Hardcoded
message from a service
5 Save all files by pressing Ctrl+Shift+S on the keyboard
The complete code for the HardcodedMessageService class:
public class HardCodedMessageService : IMessageService
Configure and Use the HardcodedMessageService Class
1 Open the Startup.cs file
2 Locate the ConfigureServices method
3 To create instances that can be swapped for the IMessage service interface
when dependency injection is used, you must add a definition for it to the
services collection In this example, you want ASP.NET to swap out the interface with an instance of the HardcodedMessageService class Add the definition by calling the AddSingleton method on the services object, specifying the interface
as the first type and the class as the second type
services.AddSingleton< IMessageService , HardcodedMessageService >();
4 Now you can use dependency injection to access the IMessageService from the Configure method, and then call the GetMessage method on the passed-in HardcodedMessageService object named msg
public void Configure( IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory, IMessageService msg)
{
}
Trang 355 Remove the line that declares the message variable from the Run block
6 Replace the message variable name in the WriteAsync method with a call to the GetMessage method on the msg object
await context.Response.WriteAsync(msg.GetMessage());
7 Save all files, switch to the browser, and refresh the application The message
Hardcoded message from a service should appear
The full code for the HardcodedMessageService class:
public class HardcodedMessageService : IMessageService
When adding a service to the service collection, you can choose between several Add
methods Here’s a rundown of the most commonly used
Singleton creates a single instance that is used throughout the application It creates the
instance when the first dependency-injected object is created
Scoped services are lifetime services, created once per request within the scope It is equivalent to Singleton in the current scope In other words, the same instance is reused
within the same HTTP request
Transient services are created each time they are requested and won’t be reused This
lifetime works best for lightweight, stateless services
Trang 36Add and Use the ConfigurationMessageService Class
1 Right click on the Services folder and select Add-Class
2 Name the class ConfigurationMessageService and click the Add button
3 Implement the IMessageService interface in the class
4 Add a constructor to the class (you can use the ctor code snippet)
5 Inject the IConfiguration interface into the constructor and name it
configuration
6 Save the configuration object in a private class level variable called
_configuration You can let Visual Studio create the variable for you by writing
the variable name in the method, clicking the lightbulb icon, and selecting
Generate field…
private IConfiguration _configuration;
public ConfigurationMessageService( IConfiguration configuration) {
_configuration = configuration;
}
7 Remove the throw statement from the GetMessage method and return the
string from the Message property stored in the appsettings.json file You achieve
this by indexing into the Configuration object
return _configuration[ "Message" ];
8 Open the Startup.cs file and locate the ConfigureServices method
9 Change the HardcodedMessageService type to the
ConfigurationMessageService type in the AddSingleton method call
services.AddSingleton< IMessageService ,
ConfigurationMessageService>();
10 Add another call to the AddSingleton method above the previous AddSingleton method call This time use the existing Configuration object and pass it to the
method’s provider using a Lambda expression This is another way to use the
Add methods when you already have an object You must add this line of code to prepare the configuration object for dependency injection
services.AddSingleton(provider => Configuration);
11 Save all files by pressing Ctrl+Shift+S on the keyboard
12 Switch over to the browser and refresh the application You should now see the
message Hello, from configuration, from the appsettings.json file
Trang 37The complete code for the ConfigurationMessageService class:
public class ConfigurationMessageService : IMessageService
{
private IConfiguration _configuration;
public ConfigurationMessageService( IConfiguration configuration) {
The complete code for the ConfigureServices method:
public void ConfigureServices( IServiceCollection services)
{
//services.AddSingleton<IMessageService, HardCodedMessageService>(); services.AddSingleton(provider => Configuration);
services.AddSingleton< IMessageService ,
ConfigurationMessageService >();
}
Trang 38Summary
In this chapter, you created your first ASP.NET application and added only the necessary pieces to get it up and running Throughout the first part of this book you will add new functionality using services and middleware
You also added a configuration file, and created and registered a service to make it able through dependency injection in other parts of the application
avail-In the next chapter, you will learn about middleware
Trang 392 Middleware
In this chapter, you will add middleware that handles HTTP requests, and how the application behaves if there is an error One key aspect of the middleware is to perform user authentication and authorization
By the end of this chapter you will have built a middleware pipeline for a MVC application How Does Middleware Work?
Let’s have a look at how middleware works and what it is used for
When a HTTP request comes to the server, it is the middleware components that handle that request
Each piece of middleware in ASP.NET is an object with a very limited, specific, and focused role This means that you will have to add many middleware components for an applica-tion to work properly
The following example illustrates what can happen when a HTTP POST request to a URL,
ending with /reviews, reaches the server
Logging is a separate middleware component that you might want to use to log tion about every incoming HTTP request It can see every piece of data, such as the head-ers, the query string, cookies, and access tokens Not only can it read data from the re-quest, it can also change information about it, and/or stop processing the request The most likely scenario with a logger is that it will log information and pass the processing onto the next middleware component in the pipeline
informa-This mean that middleware is a series of components executed in order
Trang 40The next middleware component might be an authorizer that can look at access tokens or cookies to determine if the request will proceed If the request doesn’t have the correct credentials, the authorizer middleware component can respond with a HTTP error code or redirect the user to a login page
If the request is authorized, it will be passed to the next middleware component, which might be a routing component The router will look at the URL to determine where to go next, by looking in the application for something that can respond A method on a class could be called, returning a JSON, XML, or HTML page for instance If it can’t find anything
that can respond, the component could throw a 404 Not Found error
Let’s say that it found an HTML page to respond, then the pipeline starts to call all the middleware components in reverse order, passing along the HTML When the response ultimately reaches the first component, which is the logger in our example, it might log the time the request took and then allow the response to go back over the network to the client’s browser
This is what middleware is, a way to configure how the application should behave A series
of components that handle specific, narrow tasks, such as handle errors, serve up static files and send HTTP requests to the MVC framework This will make it possible for you to build the example video application
This book will not go into the nitty-gritty of middleware, only the basics that you need to build an MVC application
IApplicationBuilder
The IApplicationBuilder interface injected into the Startup class’ Configure method is
used when setting up the middleware pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IMessageService msg)