Home Programming Modern Web Development with ASP.NET Core 3 - Second Edition

Modern Web Development with ASP.NET Core 3 - Second Edition

By Ricardo Peres
books-svg-icon Book
eBook $38.99 $26.99
Print $54.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $38.99 $26.99
Print $54.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with ASP.NET Core
About this book
ASP.NET has been the preferred choice of web developers for a long time. With ASP.NET Core 3, Microsoft has made internal changes to the framework along with introducing new additions that will change the way you approach web development. This second edition has been thoroughly updated to help you make the most of the latest features in the framework, right from gRPC and conventions to Blazor, which has a new chapter dedicated to it. You’ll begin with an overview of the essential topics, exploring the Model-View-Controller (MVC) pattern, various platforms, dependencies, and frameworks. Next, you’ll learn how to set up and configure the MVC environment, before delving into advanced routing options. As you advance, you’ll get to grips with controllers and actions to process requests, and later understand how to create HTML inputs for models. Moving on, you'll discover the essential aspects of syntax and processes when working with Razor. You'll also get up to speed with client-side development and explore the testing, logging, scalability, and security aspects of ASP.NET Core. Finally, you'll learn how to deploy ASP.NET Core to several environments, such as Azure, Amazon Web Services (AWS), and Docker. By the end of the book, you’ll be well versed in development in ASP.NET Core and will have a deep understanding of how to interact with the framework and work cross-platform.
Publication date:
June 2020
Publisher
Packt
Pages
802
ISBN
9781789619768

 
Getting Started with ASP.NET Core

Welcome to my new book on ASP.NET Core 3!

.NET and ASP.NET Core are relatively new in the technological landscape, as they were onlyofficially released in August 2017. Given that .NET is in the name, you would think that these would probably only be new versions of the highly popular .NET Framework, but that is not the case: we are talking about something that is truly new!

It's not just multiplatform support (howdy, Linux!), but it's so much more. It's the new modularity in everything: the transparent way by which we can now change things—the source code in front of our eyes teasing us to contribute to it, to make it better—is indeed a lot different from previous versions of .NET Core!

In this first chapter, we are going to talk a bit about what changed in ASP.NET and .NET in the core versions, and also about the new underlying concepts, such...

 

Technical requirements

 

Getting started

Microsoft ASP.NET was released 15 years ago, in 2002, as part of the then shiny new .NET Framework. It inherited the name ASP (short for Active Server Pages) from its predecessor, with which it barely shared anything else, other than being a technology for developing dynamic server-side content for the internet, which ran on Windows platforms only.

ASP.NET gained tremendous popularity, it has to be said, and competed hand to hand with other popular web frameworks, such as Java Enterprise Edition (JEE) and PHP. In fact, it still does, with sites such as BuiltWith giving it a share of 21% (ASP.NET and ASP.NET MVC combined), way ahead of Java (https://trends.builtwith.com/framework). ASP.NET was not just for writing dynamic web pages. It could also be used for XML (SOAP) web services, which, in early 2000, were quite popular. It benefited from the .NET Framework and its big library of classes and reusable components, which made enterprise development almost...

 

Beginning with .NET Core

Talking about ASP.NET Core without explaining .NET Core is somewhat cumbersome. .NET Core is the framework everyone is talking about, and for good reasons. ASP.NET Core is probably the most interesting API right now, as it seems that everything is moving to the web.

And why is that? Well, all these APIs relied heavily on Windows-native features; in fact, Windows Forms was merely a wrapper around the Win32 API that has accompanied Windows since its early days. Because .NET Core is multiplatform, it would be a tremendous effort to have versions of these APIs for all supported platforms. But of course, in no way does this mean that it won't happen; it's just that it hasn't happened yet.

With .NET Core, a host machine only needs a relatively small bootstrap code to run an application; the app itself needs to include all the reference libraries that it needs to operate. Interestingly, it is possible to compile a .NET Core application...

 

Dependencies and frameworks

Inside a .NET Core project, you specify the frameworks that you wish to target. What are these frameworks? Well, .NET Core itself, but the classic .NET Framework as well, Xamarin, Universal Windows Platform (UWP), Portable Class Libraries (PCL), Mono, Windows Phone, and more.

In the early days of .NET Core, you would either target .NET Core itself, or/as well as one of these other frameworks. Now it is advisable to target standards instead. Now we have .NET Standard, and the differences between the two are as follows:

  • .NET Standard is a specification (a contract) that covers which APIs a .NET platform has to implement.
  • .NET Core is a concrete .NET platform and implements the .NET Standard.
  • The latest .NET Standard will always cover the highest .NET full framework released.

David Fowler (https://twitter.com/davidfowl) of Microsoft came up with the following analogy:

interface INetStandard10...
 

Understanding the generic host

Starting with version 3.0, ASP.NET Core is now bootstrapped using a generic host. This means that it is not tied specifically to HTTP or any other web protocol, but it potentially supports any kind of protocol, including low-level TCP. The templates have changed and now the bootstrap looks something like this:

Host
.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

We are now using the Host class to create an instance of a class that implements IHostBuilder, not IWebHostBuilder, although the result is the same.

We can interfere in the bootstrap process by means of extension methods. Specifically, we can configure the following:

  • Services registration
  • Logging
  • Configuration
  • Web hosting defaults (host, startup class)

Here is a full example of changing the configuration:

Host
.CreateDefaultBuilder...
 

Understanding the MVC pattern

Let's go back to ASP.NET now. For those of you that are still working with Web Forms, what is this MVC thing anyway, and where did it come from?

Let's face it: it was pretty easy to do terrible things in Web Forms, such as add lots of sensitive code in the page (which wouldn't be compiled until the page was accessed by the browser), adding complex business logic to a page class, having several megabytes of code in View State going back and forth on every request, and so on. There was no mechanism at all, other than the developer's discretion, to do things the right way. Plus, it was terrible to unit test it, because it relied on browser submission (POST) and JavaScript to have things working properly, such as binding actions to event handlers and submitted values to controls. There had to be a different solution, and in fact, there was.

The model-view-controller (MVC) design pattern was defined in the late 1970s...

 

Getting your context

You will probably remember the HttpContext class from ASP.NET. The current instance of this class would represent the current context of execution, which included both the request information and the response channel. It was ubiquitous, and even though in Web Forms it was sometimes hidden, it was the way by which the web application communicated with the client.

Of course, ASP.NET Core also has an HttpContext class, but there is a big difference: there is no longer a Current static property that lets us get hold of the current context—instead, the process is a bit more convoluted. Anyway, all of the infrastructure classes—middleware, controllers, views, Razor pages, view components, tag helpers, and filters—allow easy access to the current context. Those who don't can leverage the IHttpContextAccessor interface through DI and get a pointer to the current context:

//this is required to register the IHttpContextAccessor...
 

Understanding the OWIN pipeline

Previous versions of ASP.NET had a very close relationship with Internet Information Services (IIS), Microsoft's flagship web server that ships with Windows. In fact, IIS was the only supported way to host ASP.NET.

Wanting to change this, Microsoft defined the Open Web Interface for .NET (OWIN) specification, which you can read about at http://owin.org. In a nutshell, it is the standard for decoupling server and application code, and for the execution pipeline for web requests. Because it is just a standard and knows nothing about the web server (if any), it can be used to extract its features.

.NET Core borrowed heavily from the OWIN specification. There are no more Global.asax, web.config, or machine.config configuration files, modules, or handlers. What we have is the following:

  • The bootstrap code in Program.Main declares a class that contains a convention-defined method (Startup will be used if no class...
 

Hosting ASP.NET Core

You probably noticed, when we talked about OWIN, that I mentioned that the sample app was hosted in Kestrel. Kestrel is the name of a platform-independent web server fully written in .NET Core (of course, using the native libraries of your operating system). You need to host your web application somewhere, and .NET Core offers the following options:

  • Kestrel: Platform independent, your host of choice if you want to have your code run on any platform.
  • WebListener: A Windows-only host, offering significant performance advantages over Kestrel, but also has the disadvantage of needing Windows; starting with ASP.NET Core 2, it is now called HTTP.sys.
  • IIS: As in the past, you can continue to host your web app in IIS, on Windows, benefiting from the old pipeline and configuration tools.

A server in this context is merely an implementation of IServer, an interface defined in the Microsoft.AspNetCore...

 

Inversion of control and dependency injection

Inversion of control (IoC) and dependency injection (DI) are two related but different patterns. The first tells us that we should not depend on actual, concrete classes, but instead on abstract base classes or interfaces that specify the functionality we're interested in.

Depending on its registrations, the IoC framework will return a concrete class that matches our desired interface or abstract base class. DI, on the other hand, is the process by which, when a concrete class is built, the dependencies it needs are then passed to its constructor (constructor injection, although there are other options). These two patterns go very well together, and throughout the book, I will use the terms IoC or DI container/framework to mean the same thing.

.NET always had support for a limited form of IoC; Windows Forms designers used it at design time to get access to the current designer's services, for example, and...

 

Knowing the environments

.NET Core has the concept of the environment. An environment is basically a runtime setting in the form of an environment variable called ASPNETCORE_ENVIRONMENT. This variable can take one of the following values (note that these are case sensitive):

  • Development: A development environment, which probably does not need much explaining
  • Staging: A preproduction environment used for testing
  • Production: An environment (or as similar as possible) in which the application will live once it is released

To be specific, you can pass any value, but these have particular significance to .NET Core. There are several ways by which you can access the current environment, but you're most likely to use one of the following methods, extension methods and properties of the IWebHostEnvironment interface (add a using reference to the Microsoft.Extensions.Hosting namespace):

  • IsDevelopment...
 

Understanding the project templates

The Visual Studio template for creating an ASP.NET Core project, since version 3.x, adds the following (or very similar) contents to the Program class:

publicstaticvoid Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}
 
publicstatic IHostBuilder CreateHostBuilder(string[] args) =>
    Host
.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(builder =>
{
builder.UseStartup<Startup>();
});

This has changed a bit since previous versions and is now more opinionated; I already showed this when talking about OWIN earlier in this chapter.

The Host class exposes the static CreateDefaultBuilder, which returns a fully built IHostBuilder instance. The CreateDefaultBuilder method is actually doing a lot of things behind our backs:

  • Creates a ConfigurationBuilder and adds the environment variables provider to it (see Chapter 2, Configuration...
 

What's new since version 2.0?

Let's see what is new in version 2.0 by going through the following sections.

ASP.NET Core 2.1

ASP.NET Core 2.1 was released on the web on May 30 2018. It doesn't contain a large number of breaking changes or fantastic new features, but I would highlight the following ones.

SignalR

SignalR, the real-time communication library for ASP.NET Core, finally made it out of prerelease. It has lots of goodies that didn't exist in pre-Core versions, and we will cover it in its own chapter.

Razor class libraries

It is now possible to package Razor UI files (.cshtml) as NuGet packages. This opens the door to lots of interesting possibilities. There will be more on this in the chapter about component reuse.

Razor pages improvements

Razor pages, introduced in ASP.NET Core 2.0, now also support areas and have a couple of additional features. We will go through them in the chapter...

 

The NuGet and dotnet tools

There are two tools that are closely related to the .NET Core SDK:

  • dotnet
  • nuget

These tools are must-haves for .NET development: the first, dotnet, is what, NuGet ecosystem of libraries and installs, publishes, and otherwise manages sets of NuGet packages. This one is

dotnet always executes with the most recent .NET Core version available on the system. In Appendix 1, you will find a good description of this tool and its usages.

You can get the nuget tool from https://www.nuget.org/packages/NuGet.CommandLine.

 

Summary

In this first chapter, we went through some of the biggest changes in ASP.NET Core and .NET Core. You are introduced to some of the key concepts in .NET Core: the NuGet distribution mode, the OWIN pipeline, the hosting model, environments, the improved context, and the built-in dependency framework, which are new in ASP.NET Core 3. We also had a look at the nuget and dotnet tools, the Swiss army knife of command-line .NET development, which will be covered in more detail in Appendix 1.

In the next chapter, we will start our .NET Core journeyby exploring the configuration of an application.

 

Questions

By now you should be able to answer the following questions:

  1. What are the benefits of DI?
  2. What are environments?
  3. What does MVC mean?
  4. What are the supported lifetimes in the built-in DI container?
  5. What is the difference between .NET Core and the .NET Standard?
  6. What is a metapackage?
  7. What is OWIN?
About the Author
  • Ricardo Peres

    Ricardo Peres is a Portuguese developer, blogger, and book author and is currently a team leader at Dixons Carphone. He has over 20 years of experience in software development and his interests include distributed systems, architectures, design patterns, and .NET development. He won the Microsoft MVP award in 2015 and has held this title up to 2020. He also authored Entity Framework Core Cookbook – Second Edition and Mastering ASP.NET Core 2.0, and was a technical reviewer for Learning NHibernate 4 for Packt. He also contributed to Syncfusion's Succinctly collection, with titles on .NET development. Ricardo maintains a blog—Development With A Dot—where he writes about technical issues. You can catch up with him on Twitter at @rjperes75.

    Browse publications by this author
Modern Web Development with ASP.NET Core 3 - Second Edition
Unlock this book and the full library FREE for 7 days
Start now