39,59 €
If you want to learn how to use ASP.NET Core with Angular effectively, this hands-on guide is for you.
Improve the way you create, debug, and deploy web applications while keeping up to date with the latest developments in .NET 8 and modern Angular, including .NET Minimal APIs and the new Angular standalone API defaults.
You’ll begin by setting up SQL Server 2022 and building a data model with Entity Framework Core. You’ll progress to fetching and displaying data, handling user input with Angular reactive forms, and implementing front-end and back-end validators for maximum effect. After that, you will perform advanced debugging and explore unit testing features with xUnit for .NET, and Jasmine and Karma for Angular. You’ll use Identity API endpoints in ASP.NET Core and functional route guards in Angular to add authentication and authorization to your apps. Finally, you’ll learn how to deploy to Windows, Linux, and Azure.
By the end of this book, you will understand how to tie together the front-end and back-end to build and deploy secure and robust web applications.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 1068
Veröffentlichungsjahr: 2024
ASP.NET Core 8 and Angular
Sixth Edition
Full-stack web development with ASP.NET Core 8 and Angular
Valerio De Sanctis
BIRMINGHAM—MUMBAI
ASP.NET Core 8 and Angular
Sixth Edition
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Senior Publishing Product Manager: Suman Sen
Acquisition Editor – Peer Reviews: Jane D'Souza
Project Editor: Janice Gonsalves
Content Development Editor: Shazeen Iqbal
Copy Editor: Safis Editing
Technical Editor: Aniket Shetty
Proofreader: Safis Editing
Indexer: Subalakshmi Govindhan
Presentation Designer: Pranit Padwal
Senior Developer Relations Marketing Executive: Priyadarshini Sharma
First published: October 2016
Second edition: November 2017
Third edition: February 2020
Fourth edition: January 2021
Fifth edition: April 2022
Sixth edition: February 2024
Production reference: 1220224
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK.
ISBN 978-1-80512-993-6
www.packt.com
Valerio De Sanctis is a skilled IT professional with more than 20 years of experience in lead programming, web-based development, and project management using ASP.NET, PHP, and Java. He held senior positions at a range of financial and insurance companies, most recently serving as Chief Technology Officer, Chief Security Officer, and Chief Operating Officer at a leading after-sales and IT service provider for multiple top-tier life and non-life insurance groups. He’s also one of Microsoft’s Most Valuable Professional (MVP) for Developer Technologies and Cloud and Datacenter Management.
He has written various books on web development, many of which have become best-sellers on Amazon, with tens of thousands of copies sold worldwide.
I would like to thank those who supported me in writing this book: my beloved and beautiful wife, Carla, for her awesome encouragement and invaluable support; my children, Viola and Daniele; and my parents and sister. Last, but not least, I want to thank you, the reader, for picking up this book. I really hope you will enjoy it!
Wouter Huysentruit is a seasoned software developer and architect with over 20 years of experience across various fields. He aims to create solutions that are both easy to understand and maintain. Currently, his focus lies in developing user-friendly web applications utilizing Microsoft technologies and Angular, alongside contributing to numerous open-source projects, where he has been honored with the Microsoft MVP award.
A big thanks goes out to my wife and kids for supporting me during the review of this book.
Join our community’s Discord space for discussions with the author and other readers:
https://packt.link/aspdotnet8angular
Preface
Who this book is for
What this book covers
To get the most out of this book
Get in touch
Introducing ASP.NET and Angular
Technical requirements
Two players, one goal
The ASP.NET Core revolution
ASP.NET Core 1.x
ASP.NET Core 2.x
ASP.NET Core 3.x
.NET 5
.NET 6
.NET 7
.NET 8
What’s new in Angular?
GetAngular
AngularJS
Angular 2
Angular 4
Angular 5
Angular 6
Angular 7
Angular 8
Angular 9
Angular 10
Angular 11
Angular 12
Angular 13
Angular 14
Angular 15
Angular 16
Angular 17
Reasons for choosing .NET and Angular
Summary
Suggested topics
References
Getting Ready
Technical requirements
A full-stack approach
MPAs, SPAs, PWAs, and NWAs
Multi-page applications
Single-page applications
Progressive web applications
Native web applications
Product owner expectations
An example SPA project
Not your usual Hello World!
Preparing the workspace
Disclaimer — do (not) try this at home
The broken code myth
Stay hungry, stay foolish, yet be responsible as well
Setting up the project(s)
Installing the .NET 8 SDK
Checking the SDK version
Installing Node.js and the Angular CLI
Creating the Angular and ASP.NET Core project
Performing a test run
Troubleshooting
Architecture overview
Summary
Suggested topics
References
Looking Around
Technical requirements
Solution overview
The ASP.NET back-end
Configuration files
Program.cs
appsettings.json
Controllers
WeatherForecastController
Introducing OpenAPI (Swagger)
The Angular front-end
The root files
angular.json
package.json
tsconfig.json
Other workspace-level files
The /src/ folder
The /src/app/ folder
Our first test run
First testing attempt
Getting to work
Changing the API endpoints
Implementing a baseUrl property
Refactoring the Angular app
Adding HomeComponent
Adding FetchDataComponent
Adding the navigation menu
Updating the AppComponent
Updating the AppRoutingModule
Finishing touches
Test run
Summary
Suggested topics
References
Front-End and Back-End Interactions
Technical requirements
Introducing ASP.NET Core health checks
Adding the HealthCheck middleware
Adding an Internet Control Message Protocol (ICMP) check
Possible outcomes
Creating an ICMPHealthCheck class
Adding the ICMPHealthCheck
Improving the ICMPHealthCheck class
Adding parameters and response messages
Updating the middleware setup
Implementing a custom output message
Configuring the output message
Health checks in Angular
Creating the Angular component
health-check.component.ts
health-check.component.html
health-check.component.css
Adding the component to the Angular app
AppRoutingModule
NavMenuComponent
Testing it out
Restyling the UI
Introducing Angular Material
Installing Angular Material
Adding a MatToolbar
Updating the AppModule
Updating the NavMenuComponent HTML template
First test run
Playing with (S)CSS
Introducing Sass
Replacing CSS with Sass
Restyling the tables
Summary
Suggested topics
References
Data Model with Entity Framework Core
Technical requirements
The WorldCities web app
Updating the ASP.NET Core app
Updating the Angular app
Minimal UI restyling
Reasons to use a data server
The data source
The data model
Introducing Entity Framework Core
Installing Entity Framework Core
The SQL Server Data Provider
DBMS licensing models
What about Linux?
SQL Server alternatives
Data modeling approaches
Code-First
Database-First
Making a choice
Creating the entities
Defining the entities
The City entity
The Country entity
Should we (still) use #region blocks?
Defining relationships
Adding the Country property to the City entity class
Adding the Cities property to the Country entity class
Defining the database table names
Defining indexes
Getting a SQL Server instance
Installing SQL Server 2022
Installing the database management tool(s)
Creating a SQL database on Azure
SQL Database
SQL Managed Instance
SQL virtual machine
Making a choice
Setting up a SQL database
Configuring the instance
Configuring the database
Creating the WorldCities database
Adding the WorldCities login
Mapping the login to the database
Creating the database using Code-First
Setting up the DbContext
Entity type configuration methods
Data annotations
Fluent API
EntityTypeConfiguration classes
Making a choice
Database initialization strategies
Updating the appsettings.json file
Securing the connection string
Introducing Secrets Storage
Adding the secrets.json file
Working with the secrets.json file
Creating the database
Updating Program.cs
Adding the initial migration
Using the dotnet CLI
Using the Package Manager Console
Checking the autogenerated database tables
Understanding migrations
Populating the database
Implement SeedController
Import the Excel file
Entity controllers
CitiesController
CountriesController
Should we really use entities?
Testing it out
Summary
Suggested topics
References
Fetching and Displaying Data
Technical requirements
Fetching data
Requests and responses
JSON conventions and defaults
A (very) long list
city.ts
cities.component.ts
cities.component.html
cities.component.scss
app-routing.module.ts
nav-component.html
Serving data with Angular Material
Adding AngularMaterialModule
Introducing MatTable
Updating AngularMaterialModule
Updating CitiesComponent
Adding pagination with MatPaginatorModule
Client-side paging
Server-side paging
Adding sorting with MatSortModule
Extending ApiResult
Installing System.Linq.Dynamic.Core
Updating CitiesController
Updating the Angular app
Adding filtering
Extending ApiResult (again)
CitiesController
CitiesComponent
CitiesComponent template (HTML) file
CitiesComponent style (SCSS) file
AngularMaterialModule
Performance considerations
Adding countries to the loop
ASP.NET
CountriesController
Angular
country.ts
countries.component.ts
countries.component.html
countries.component.scss
AppModule
AppRoutingModule
NavComponent
Testing CountriesComponent
Summary
Suggested topics
ASP.NET
Angular
References
Forms and Data Validation
Technical requirements
Exploring Angular forms
Forms in Angular
Reasons to use forms
Template-driven forms
The pros
The cons
Model-driven/Reactive Forms
Building our first Reactive Form
ReactiveFormsModule
CityEditComponent
city-edit.component.ts
city-edit.component.html
city-edit.component.scss
Adding the navigation link
app-routing.module.ts
cities.component.html
Adding a new city
Extending the CityEditComponent
Adding the “Add a new City” button
Adding a new route
HTML select
Angular Material select (MatSelectModule)
Understanding data validation
Template-driven validation
Model-driven validation
Our first validators
Testing the validators
Server-side validation
DupeCityValidator
Introducing the FormBuilder
Creating the CountryEditComponent
country-edit.component.ts
The IsDupeField server-side API
country-edit.component.html
country-edit.component.scss
AppRoutingModule
CountriesComponent
Testing the CountryEditComponent
Improving the filter behavior
Throttling and debouncing
Definitions
Why would we want to throttle or debounce our code?
Debouncing calls to the back-end
Updating the CitiesComponent
Updating the CountriesComponent
What about throttling?
Summary
Suggested topics
References
Code Tweaks and Data Services
Technical requirements
Optimizations and tweaks
Template improvements
Form validation shortcuts
Class inheritance
Implementing a BaseFormComponent
Extending CountryEditComponent
Extending CityEditComponent
Bug fixes and improvements
Validating lat and lon
city-edit.component.ts
base-form.component.ts
city-edit.component.html
Adding the number of cities
CountriesController
Creating the CountryDTO class
Angular front-end updates
DTO classes – should we really use them?
Separation of concerns
Security considerations
DTO classes versus anonymous types
Securing entities
Final thoughts
Adding the country name
CitiesController
Angular front-end updates
Data services
XMLHttpRequest versus Fetch (versus HttpClient)
XMLHttpRequest
Fetch
HttpClient
Building a data service
Creating the BaseService
Adding the common interface methods
Creating CityService
Implementing CityService
Creating CountryService
Summary
Suggested topics
References
Back-End and Front-End Debugging
Technical requirements
Backend debugging
Windows or Linux?
The basics
Conditional breakpoints
Conditions
Actions
Testing the conditional breakpoint
The Output window
LogLevel types
Testing the LogLevel
Configuring the Output window
Debugging EF Core
The GetCountries() SQL query
Frontend debugging
Visual Studio JavaScript debugging
JavaScript source maps
Browser developer tools
Angular form debugging
A look at the Form Model
The pipe operator
Reacting to changes
The activity log
Client-side debugging
Unsubscribing the Observables
The unsubscribe() method
The takeUntil() operator
Other viable alternatives
Should we always unsubscribe?
Application logging
Introducing ASP.NET Core logging
Database Management System (DBMS) structured logging with Serilog
Installing the NuGet packages
Configuring Serilog
Logging HTTP requests
Accessing the logs
Summary
Suggested topics
References
ASP.NET Core and Angular Unit Testing
Technical requirements
ASP.NET Core unit tests
Creating the WorldCities.Server.Tests project
Moq
Microsoft.EntityFrameworkCore.InMemory
Adding the WorldCities dependency reference
Our first test
Arrange
Act
Assert
Executing the test
Debugging tests
Test-driven development
Behavior-driven development
Angular unit tests
General concepts
Introducing the TestBed interface
Testing with Jasmine
Our first Angular test suite
The import section
The describe and beforeEach sections
Adding a mock CityService
Implementing the mock CityService
Configuring the fixture and the component
Creating the title test
Creating the cities tests
Running the test suite
Summary
Suggested topics
References
Authentication and Authorization
Technical requirements
To auth, or not to auth?
Authentication
Authentication methods
Third-party authentication
Authorization
Proprietary authorization
Third-party authorization
Proprietary versus third-party
Proprietary auth with ASP.NET Core
The ASP.NET Core Identity model
Entity types
Setting up ASP.NET Core Identity
Adding the NuGet packages
Creating ApplicationUser
Extending ApplicationDbContext
Configuring the ASP.NET Core Identity service
Implementing AccountController
Configuring JwtBearerMiddleware
Updating SeedController
Securing the action methods
A word on async tasks, awaits, and deadlocks
Updating the database
Adding identity migration
Applying the migration
Updating the existing data model
Dropping and recreating the data model from scratch
Seeding the data
Implementing authentication in Angular
Adding the LoginRequest interface
Adding the LoginResult interface
Implementing AuthService
Creating LoginComponent
login.component.ts
login.component.html
login.component.scss
Updating AppRoutingModule
Updating NavMenuComponent
Testing LoginComponent
Adding the authStatus observable
Updating the UI
Testing the observable
HttpInterceptors
Implementing AuthInterceptor
Updating AppModule
Testing HttpInterceptor
Route Guards
Available guards
Implementing AuthGuard
Updating AppRoutingModule
Testing AuthGuard
Finishing touches
Identity API endpoints
Activating the Identity API endpoints
Testing the endpoints
Should we use the Identity API endpoints?
Summary
Suggested topics
References
Progressive Web Apps
Technical requirements
PWA distinctive features
Secure origin
Offline loading
Service workers versus HttpInterceptors
Introducing @angular/service-worker
Implementing the PWA requirements
Manual installation
Adding the @angular/service-worker npm package
Updating the angular.json file
Importing ServiceWorkerModule
Updating the index.html file
Adding the Web App Manifest file
Adding the favicon
Adding the ngsw-config.json file
Automatic installation
The Angular PNG icon set
Handling the offline status
Option 1 – the window’s ononline/onoffline events
Option 2 – the navigator.onLine property
Downsides of the JavaScript approaches
Option 3 – the ng-connection-service npm package
Installing the service
Updating the AppModule file
Updating the AppComponent
Adding the api/heartbeat endpoint
Introducing Minimal APIs
Cross-Origin Resource Sharing
Implementing CORS
Testing the PWA capabilities
Compiling the app
Installing http-server
Testing out our PWAs
Installing the PWA
Summary
Suggested topics
References
Beyond REST – Web API with GraphQL
Technical requirements
GraphQL versus REST
REST
Guiding constraints
Drawbacks
GraphQL
Advantages over REST
Limitations
Implementing GraphQL
Adding GraphQL to ASP.NET Core
Installing HotChocolate
Testing the GraphQL schema
Adding GraphQL to Angular
Installing Apollo Angular
Refactoring CityService
Refactoring CountryService
Summary
Suggested topics
References
Real-Time Updates with SignalR
Technical requirements
Real-time HTTP and server push
Introducing SignalR
Hubs
Protocols
Connections, users, and groups
Implementing SignalR
Setting up SignalR in ASP.NET Core
Creating the HealthCheckHub
Setting up services and middleware
Adding the broadcast message
Installing SignalR in Angular
Adding the npm package
Implementing the HealthCheckService
Adding WebSocket support to Angular proxy
Refactoring the HealthCheckComponent
Testing it all
Client-initiated events
Updating the HealthCheckHub
Updating the HealthCheckService
Updating the HealthCheckComponent
Testing the new feature
Summary
Suggested topics
References
Windows, Linux, and Azure Deployment
Technical requirements
Getting ready for production
Configuring the endpoints
Tweaking the HOSTS file
Other viable alternatives
ASP.NET Core deployment tips
The launchSettings.json file
Runtime environments
.NET deployment modes
Angular deployment tips
ng serve, ng build, and the package.json file
Differential loading
The angular.json configuration file(s)
Updating the environment.ts file(s)
Automatic deployment
Windows deployment
Creating a Windows Server VM on MS Azure
Accessing the MS Azure portal
Adding a new Windows VM
Configuring a DNS name label
Setting the inbound security rules
Configuring the Windows VM
Adding the IIS web server
Installing the ASP.NET Core Windows hosting bundle
Publishing healthcheck.client and HealthCheck.Server
Introducing Visual Studio publish profiles
Folder publish profile
FTP publish profile
Azure Virtual Machine publish profile
Configuring IIS
Adding the healthcheck.client website entry
Adding the HealthCheck.Server website entry
A note on TLS/SSL certificates
Configuring the IIS application pool
Adding the .webmanifest MIME type
Testing healthcheck.client and HealthCheck.Server
Testing the app
Linux deployment
Creating a Linux VM on MS Azure
Adding a new Linux VM
Configuring a DNS name label
Setting the inbound security rules
Configuring the Linux VM
Connecting to the VM
Installing the ASP.NET Core Runtime
Installing Nginx
Opening the 80 and 443 TCP ports
Publishing worldcities.client and WorldCities.Server
Building the Angular app
Building the WorldCities.Server app
Deploying the files to the Linux VM
Configuring Kestrel and Nginx
Testing WorldCities and WorldCities.Server
Testing the app
Troubleshooting
Azure App Service deployment
Creating the App Service instances
Adding the healthcheck.client Static Web App
Adding the HealthCheck.Server Web App
Adapting our apps for App Service
Publishing our apps to App Service
Publishing the Angular app
Publishing the ASP.NET Core project
Testing healthcheck.client and HealthCheck.Server
Summary
Suggested topics
References
Other Books You May Enjoy
Index
Cover
Index
Once you’ve read ASP.NET Core 8 and Angular, Sixth Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below:https://packt.link/free-ebook/9781805129936
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyOver the first two chapters of this book, we’ll build the basics of our ASP.NET and Angular journey by mixing theoretical coverage of their most relevant features with a practical approach. More specifically, in the first chapter, we’ll briefly review the recent history of ASP.NET/.NET Core and Angular frameworks, while in the second chapter, we’ll learn how to configure our local development environment so we can assemble, build, and test a sample web application boilerplate.
By the end of these chapters, you’ll have gained knowledge of the path taken by ASP.NET and Angular to improve web development in the last few years and learned how to properly set up an ASP.NET and Angular web application.
Here are the main topics that we are going to cover in this chapter:
Two players, one goal: How ASP.NET and Angular can be used together to build a modern, feature-rich, and highly versatile web applicationThe ASP.NET Core revolution: A brief history of ASP.NET’s most recent achievementsWhat’s new in Angular: A recap of the Angular development journey, from its origins to the most recent daysThese are the software packages (and relevant version numbers) used to write this book and test the source code:
Visual Studio 2022 Community edition 17.8.1 with the optional ASP.NET and web development workload (it can be selected from the Workloads section within the Visual Studio installer app)Microsoft .NET 8 SDK 8.0.100TypeScript 5.2NuGet package manager 6.8.0Node.js 20.10.0Angular 17.0.3We strongly suggest using the same version used within this book, or newer, but at your own risk! Jokes aside, if you prefer to use a different version, that’s perfectly fine, as long as you are aware that, in that case, you may need to make some manual changes and adjustments to the source code.
The code files for this book can be found here: https://github.com/PacktPublishing/ASP.NET-Core-8-and-Angular.
From the perspective of a fully functional web-based application, we can say that the web API interface provided with the ASP.NET framework is a programmatic set of server-side handlers used by the server to expose a number of hooks and/or endpoints to a defined request-response message system. This is typically expressed in structured markup languages (XML), language-independent data formats (JSON), or query languages for APIs (GraphQL). As we’ve already said, this is achieved by exposing application programming interfaces (APIs) through HTTP and/or HTTPS protocols via a publicly available web server such as IIS, Node.js, Apache, or NGINX.
Similarly, Angular can be described as a modern, feature-rich, client-side framework that pushes the HTML and ECMAScript’s most advanced features, along with the modern browser’s capabilities, to their full extent by binding the input and/or output parts of an HTML web page into a flexible, reusable, and easily testable model.
Can we combine the back-end strengths of ASP.NET and the front-end capabilities of Angular in order to build a modern, feature-rich, and highly versatile web application?
The answer, in short, is yes. In the following sections, we’ll see how we can do that by analyzing all the fundamental aspects of a well-written, properly designed, web-based product, and how the latest versions of ASP.NET and/or Angular can be used to handle each one of them. However, before doing all that, it might be very useful to backtrack a bit and spend some valuable time recollecting what’s happened in the last 8 years in the development history of the two frameworks we’re going to use. It will be very useful to understand the main reasons why we’re still giving them full credit, despite the valuable efforts of their ever-growing competitors.
To summarize what has happened in the ASP.NET world within the last decade is not an easy task; in short, we can say that we’ve undoubtedly witnessed the most important series of changes in .NET Framework since the year it came to life. This was a revolution that changed the whole Microsoft approach to software development in almost every way. To properly understand what happened in those years, it would be useful to identify some distinctive key frames within a slow, yet constant, journey that allowed a company known (and somewhat loathed) for its proprietary software, licenses, and patents to become a driving force for open source development worldwide.
The first relevant step, at least in my humble opinion, was taken on April 3, 2014, at the annual Microsoft Build conference, which took place at the Moscone Center (West) in San Francisco. It was there, during a memorable keynote speech, that Anders Hejlsberg – father of Delphi and lead architect of C# – publicly released the first version of the .NET Compiler Platform, known as Roslyn, as an open source project. It was also there that Scott Guthrie, executive vice president of the Microsoft Cloud and AI group, announced the official launch of .NET Foundation, a non-profit organization aimed at improving open source software development and collaborative work within the .NET ecosystem.
From that pivotal day, the .NET development team published a constant flow of Microsoft open source projects on the GitHub platform, including Entity Framework Core (May 2014), TypeScript (October 2014), .NET Core (October 2014), CoreFX (November 2014), CoreCLR and RyuJIT (January 2015), MSBuild (March 2015), the .NET Core CLI (October 2015), Visual Studio Code (November 2015), .NET Standard (September 2016), and so on.
The most important achievement brought by these efforts toward open source development was the public release of ASP.NET Core 1.0, which came out in Q3 2016. It was a complete reimplementation of the ASP.NET framework that we had known since January 2002 and that had evolved, without significant changes in its core architecture, up to version 4.6.2 (August 2016). The brand-new framework united all the previous web application technologies, such as MVC, Web API, and web pages, into a single programming module, formerly known as MVC6. The new framework introduced a fully featured, cross-platform component, also known as .NET Core, shipped with the whole set of open source tools mentioned previously, namely, a compiler platform (Roslyn), a cross-platform runtime (CoreCLR), and an improved x64 Just-In-Time compiler (RyuJIT).
Some of you might remember that ASP.NET Core was originally called ASP.NET 5. As a matter of fact, ASP.NET 5 was no less than the original name of ASP.NET Core until mid-2016, when the Microsoft developer team chose to rename it to emphasize the fact that it was a complete rewrite. The reasons for that, along with the Microsoft vision about the new product, are further explained in the following Scott Hanselman blog post that anticipated the changes on January 16, 2016: http://www.hanselman.com/blog/ASPNET5IsDeadIntroducingASPNETCore10AndNETCore10.aspx.
For those who don’t know, Scott Hanselman has been the outreach and community manager for .NET/ASP.NET/IIS/Azure and Visual Studio since 2007. Additional information regarding the perspective switch is also available in the following article by Jeffrey T. Fritz, program manager for Microsoft and a NuGet team leader: https://blogs.msdn.microsoft.com/webdev/2016/02/01/an-update-on-asp-net-core-and-net-core/.
As for Web API 2, it was a dedicated framework for building HTTP services that returned pure JSON or XML data instead of web pages. Initially born as an alternative to the MVC platform, it has been merged with the latter into the new, general-purpose web application framework known as MVC6, which is now shipped as a separate module of ASP.NET Core.
The 1.0 final release was shortly followed by ASP.NET Core 1.1 (Q4 2016), which introduced some new features and performance enhancements and also addressed many bugs and compatibility issues affecting the earlier release. These new features include the ability to configure middleware as filters (by adding them to the MVC pipeline rather than the HTTP request pipeline); a built-in, host-independent URL rewrite module, made available through the dedicated Microsoft.AspNetCore.Rewrite NuGet package; view components as tag helpers; view compilation at runtime instead of on-demand; and .NET native compression and caching middleware modules.
For a detailed list of all the new features, improvements, and bug fixes in ASP.NET Core 1.1, check out the following links:
Release notes: https://github.com/aspnet/AspNetCore/releases/1.1.0Commits list: https://github.com/dotnet/core/blob/master/release-notes/1.1/1.1-commits.mdAnother major step was taken with ASP.NET Core 2.0, which came out in Q2 2017 as a preview and then in Q3 2017 for the final release. The new version featured a wide number of significant interface improvements, mostly aimed at standardizing the shared APIs among .NET Framework, .NET Core, and .NET Standard to make them backward-compatible with .NET Framework. Thanks to these efforts, moving existing .NET Framework projects to .NET Core and/or .NET Standard became a lot easier than before, giving many traditional developers a chance to try and adapt to the new paradigm without losing their existing know-how.
Again, the major version was shortly followed by an improved and refined one: ASP.NET Core 2.1. This was officially released on May 30, 2018, and introduced a series of additional security and performance improvements, as well as a bunch of new features, including SignalR, an open source library that simplifies adding real-time web functionality to .NET Core apps; Razor class libraries; a significant improvement in the Razor SDK that allows developers to build views and pages into reusable class libraries, and/or library projects that could be shipped as NuGet packages; the Identity UI library and scaffolding, to add identity to any app and customize it to meet your needs; HTTPS support enabled by default; built-in General Data Protection Regulation (GDPR) support using privacy-oriented APIs and templates that give users control over their personal data and cookie consent; updated SPA templates for Angular and ReactJS client-side frameworks; and much more.
For a detailed list of all the new features, improvements, and bug fixes in ASP.NET Core 2.1, check out the following links:
Release notes: https://docs.microsoft.com/en-US/aspnet/core/release-notes/aspnetcore-2.1Commits list: https://github.com/dotnet/core/blob/master/release-notes/2.1/2.1.0-commit.mdWait a minute: did we just say Angular? Yeah, that’s right. As a matter of fact, since its initial release, ASP.NET Core has been specifically designed to seamlessly integrate with popular client-side frameworks such as ReactJS and Angular. It is precisely for this reason that books such as this exist. The major difference introduced in ASP.NET Core 2.1 is that the default Angular and ReactJS templates have been updated to use the standard project structures and build systems for each framework (the Angular CLI and NPX’s create-react-app command) instead of relying on task runners such as Grunt or Gulp, module builders such as webpack, or toolchains such as Babel, which were widely used in the past, although they were quite difficult to install and configure.
Being able to eliminate the need for these tools was a major achievement, which has played a decisive role in revamping the .NET Core usage and growth rate among the developer communities since 2017. If you take a look at the two previous installments of this book – ASP.NET Core and Angular 2, published in mid-2016, and ASP.NET Core 2 and Angular 5, out in late 2017 – and compare their first chapter with this one, you will see the huge difference between having to manually use Gulp, Grunt, or webpack, and relying on the integrated framework-native tools. This is a substantial reduction in complexity that would greatly benefit any developer, especially those less accustomed to working with those tools.
Six months after the release of the 2.1 version, the .NET Foundation came out with a further improvement: ASP.NET Core 2.2 was released on December 4, 2018, with several fixes and new features, including an improved endpoint routing system for better dispatching of requests, updated templates featuring Bootstrap 4 and Angular 6 support, and a new health checks service to monitor the status of deployment environments and their underlying infrastructures, including container orchestration systems such as Kubernetes, built-in HTTP/2 support in Kestrel, and a new SignalR Java client to ease the usage of SignalR within Android apps.
For a detailed list of all the new features, improvements, and bug fixes in ASP.NET Core 2.2, check out the following links:
Release notes: https://docs.microsoft.com/en-US/aspnet/core/release-notes/aspnetcore-2.2Commits list: https://github.com/dotnet/core/blob/master/release-notes/2.2/2.2.0/2.2.0-commits.mdASP.NET Core 3 was released in September 2019 and came with another bunch of performance and security improvements and new features, such as:
Windows desktop application support (Windows only) with advanced importing capabilities for Windows Forms and Windows Presentation Foundation (WPF) applicationsC# 8 support.NET Platform-dependent intrinsic access through a new set of built-in APIs that could bring significant performance improvements in certain scenariosSingle-file executable support via the dotnet publish command using the <PublishSingleFile> XML element in project configuration or through the /p:PublishSingleFile command-line parameterNew built-in JSON support featuring high performance and low allocation that’s arguably two to three times faster than the JSON.NET third-party library (which became the de facto standard in most ASP.NET web projects)TLS 1.3 and OpenSSL 1.1.1 support in LinuxSome important security improvements in the System.Security.Cryptography namespace, including AES-GCM and AES-CCM cipher support; and so onA lot of work has also been done to improve the performance and reliability of the framework when used in a containerized environment. The ASP.NET Core development team put a lot of effort into improving the .NET Core Docker experience on .NET Core 3.0. More specifically, this is the first release featuring substantive runtime changes to make CoreCLR more efficient, honor Docker resource limits better (such as memory and CPU) by default, and offer more configuration tweaks. Among the various improvements, we could mention improved memory and GC heap usage by default, and PowerShell Core, a cross-platform version of the famous automation and configuration tool, which is now shipped with the .NET Core SDK Docker container images.
.NET Core 3 also introduced Blazor, a free and open source web framework that enables developers to create web apps using C# and HTML.
Last but not least, it’s worth noting that the new .NET Core SDK is much smaller than the previous installments, mostly thanks to the fact that the development team removed a huge set of unnecessary artifacts included in the various NuGet packages that were used to assemble the previous SDKs (including ASP.NET Core 2.2) from the final build. The size improvements are huge for Linux and macOS versions, while less noticeable on Windows because that SDK also contains the new WPF and Windows Forms set of platform-specific libraries.
For a detailed list of all the new features, improvements, and bug fixes in ASP.NET Core 3.0, check out the following links:
Release notes: https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0ASP.NET Core 3.0 releases page: https://github.com/dotnet/core/tree/master/release-notes/3.0ASP.NET Core 3.1 was released on December 3, 2019. Most of the updates were fixes related to Blazor, such as preventing default actions for events and stopping event propagation in Blazor apps, partial class support for Razor components, and additional Tag Helper Component features; however, much like the other .1 releases, the primary goal of .NET Core 3.1 was to refine and improve the features already delivered in the previous version, with more than 150 performance and stability issues fixed.
A detailed list of the new features, improvements, and bug fixes introduced with ASP.NET Core 3.1 is available at the following URL:
Release notes: https://learn.microsoft.com/en-us/aspnet/core/release-notes/aspnetcore-3.1Just when everyone thought that Microsoft had finally taken a clear path with the naming convention of its upcoming frameworks, the Microsoft developer community was shaken again on May 6, 2019, by the following post by Richard Lander, Program Manager of the .NET team, which appeared on the Microsoft Developer Blog: https://devblogs.microsoft.com/dotnet/introducing-net-5/.
The post got an immediate backup from another article that came out the same day written by Scott Hunter, Program Management Director of the .NET ecosystem: https://devblogs.microsoft.com/dotnet/net-core-is-the-future-of-net/.
The two posts were meant to share the same big news with the readers: .NET Framework 4.x and .NET Core 3.x would converge in the next major installment of .NET Core, which would skip a major version number to properly encapsulate both installments.
The new unified platform would be called .NET 5 and would include everything that had been released so far with uniform capabilities and behaviors: .NET Runtime, JIT, AOT, GC, BCL (Base Class Library), C#, VB.NET, F#, ASP.NET, Entity Framework, ML.NET, WinForms, WPF, and Xamarin.
Microsoft said they wanted to eventually drop the term “Core” from the framework name because .NET 5 would be the main implementation of .NET going forward, thus replacing .NET Framework and .NET Core. However, for the time being, the ASP.NET Core ecosystem is still retaining the name “Core” to avoid confusing it with ASP.NET MVC 5; Entity Framework Core will also keep the name “Core” to avoid confusing it with Entity Framework 5 and 6. For all of these reasons, in this book, we’ll keep using “ASP.NET Core” and “Entity Framework Core” (or “EF Core”) as well.
From Microsoft’s point of view, the reasons behind this bold choice were rather obvious:
Produce a single .NET runtime and framework that can be used everywhere and that has uniform runtime behaviors and developer experiencesExpand the capabilities of .NET by taking the best of .NET Core, .NET Framework, Xamarin, and MonoBuild that product out of a single code base that internal (Microsoft) and external (community) developers can work on and expand together and that improves all scenariosThe new name could reasonably generate some confusion among those developers who still remember the short timeframe (early to mid-2016) in which ASP.NET Core v1 was still called ASP.NET 5 before its final release. Luckily enough, that “working title” was ditched by the Microsoft developer team and the .NET community before it could leave noticeable traces on the web.
.NET 5 was released on General Availability in November 2020, a couple of months after its first Release Candidate, thus respecting the updated .NET schedule that aims to ship a new major version of .NET once a year, every November:
Figure 1.1: .NET schedule
In addition to the new name, the .NET 5 framework brought a lot of interesting changes, such as:
Performance improvements and measurement tools, summarized in this great analysis performed by Stephen Toub (.NET Partner Software Engineer) using the new Benchmark.NET tools: https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-5/.Half Type, a binary floating point that occupies only 16 bits and that can help to save a good amount of storage space where the computed result does not need to be stored with full precision. For additional info, take a look at this post by Prashanth Govindarajan (Senior Engineering Manager at LinkedIn): https://devblogs.microsoft.com/dotnet/introducing-the-half-type/.Assembly trimming, a compiler-level option to trim unused assemblies as part of publishing self-contained applications when using the self-contained deployment option, as explained by Sam Spencer (.NET Core team Program Manager) in this post: https://devblogs.microsoft.com/dotnet/app-trimming-in-net-5/.Various improvements in the new System.Text.Json API, including the ability to ignore default values for value-type properties when serializing (for better serialization performance) and to better deal with circular references.C# 9 and F# 5 language support, with a bunch of new features such as Init Only Setters (that allows the creation of immutable objects), function pointers, static anonymous functions, target-typed conditional expressions, covariant return types, and module initializers.And a lot of other new features and improvements besides.
A detailed list of the new features and improvements and a comprehensive explanation of the reasons behind the release of ASP.NET 5 are available at the following URL:
Release notes: https://docs.microsoft.com/en-us/dotnet/core/dotnet-fiveFor additional info about the C# 9.0 new features, take a look at the following URL: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9.
.NET 6 came out on November 8, 2021, a year after .NET 5, as expected by the .NET schedule. The most notable improvement in this version is the introduction of the Multi-platform Application UI, also known as MAUI: a modern UI toolkit built on top of Xamarin.Forms that was specifically created to eventually replace Xamarin.Forms and become the .NET standard for creating multi-platform applications that can run on Android, iOS, macOS, and Windows from a single code base.
The main difference between MAUI and Xamarin is that the new approach now ships as a core workload, shares the same base class library as other workloads (such as Blazor), and adopts the most recent SDK Style project system introduced with .NET 5, thus allowing a consistent tooling and coding experience for all .NET developers.
In addition to MAUI, .NET 6 introduces a lot of new features and improvements, such as:
C# 10 language support, with some new features such as null parameter checking, required properties, field keyword, file-scoped namespaces, top-level statements, async main, target-typed new expressions, and more.Implicit using directives, a feature that instructs the compiler to automatically import a set of using statements based on the project type, without the need to explicitly include them in each file.New project templates, which are much cleaner and simpler since they do implement (and demonstrate) most of the language improvements brought by C# version 9 and 10 (including those we’ve just mentioned).Package Validation tooling, an option that allows developers to validate that their packages are consistent and well formed during package development.SDK workloads, a feature that leverages the concepts of “workloads” introduced with .NET Core to allow developers to install only necessary SDK components, skipping the parts they don’t need: in other words, it’s basically a “package manager” for the SDKs.Inner-loop performance improvements, a family of tweaks dedicated to the performance optimization of the various tools and workflows used by developers (such as CLI, runtime, and MSBuild), thereby aiming to improve their coding and building experience. The most important of them is the hot reload, a feature that allows the project’s source code to be modified while the application is running, without the need to manually pause or hit a breakpoint.For a comprehensive list of the new C# 10 features, check out the following URL: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10.
.NET 7 came out on November 8, 2022 and was mostly focused on performance: it was presented by Microsoft as “unified, modern, simple, and fast.” The optimizations include enhancements to the Just-In-Time (JIT) compiler, garbage collector improvements, and runtime updates.
One of the most praised changes was the introduction of on-stack replacement (OSR), a feature that allows the runtime to change the code executed by currently running methods. Thanks to OSR, long-running methods can switch to more optimized versions during their execution, thus improving the overall startup time.
For additional information on how OSR works, check out the official documentation:
https://github.com/dotnet/runtime/blob/main/docs/design/features/OnStackReplacement.md
Other improvements include:
Faster code generation for Arm64 architectures.Several optimizations to the Mono runtime.New APIs and improvements to the System.Text.RegularExpressions and System.Text.Json libraries.New metrics for the IMemoryCache interface (part of Microsoft.Extensions.Caching library) that allow developers to track statistics for one or more memory caches.Added support for microseconds and nanoseconds in TimeSpan, TimeOnly, DateTime, and DateTimeOffset types.Added a new rate-limiting middleware (Microsoft.AspNetCore.RateLimiting) that allows developers to configure several rate-limiting policies and attach them to the HTTP endpoints using the [EnableRateLimiting] attribute. The built-in rate limiting algorithms include fixed window, sliding window, token bucket, and concurrency.HTTP/3 improved support.HTTP/2 performance improvements.Coming out on November 14, 2023, .NET 8 is the successor of .NET 7 and the current long-term support (LTS) release. The new version brings a lot of performance improvements and new features, including:
A revamp of the serialization and deserialization functionalities provided by the System.Text.Json library, such as built-in support for Half, Int128, and Uint128 numeric types; new naming policies (snake_case and kebab-case); read-only properties deserialization; and several new extension methodsMany improvements to globalization, including better support for different cultures, UTF8 support, and improved performance for globalization-related operationsOn the ASP.NET Core side, the new release adds several new features to authentication and authorization, such as:
New ASP.NET Core Identity API endpoints — /register and /login — to ease up the implementation of the built-in authentication workflow in JavaScript-based single-page apps (SPAs)A new IAuthorizationRequirementData interface that allows to define custom authorization policies with fewer lines of codeA lot of progress has also been made on Blazor, which can now be considered a full-stack web UI framework that can render content at either the component or page level, in a number of ways:
Static server rendering(SSR), to generate static HTML on the serverInteractive server rendering (ISR), to generate interactive components with prerendering on the serverInteractive WebAssembly rendering (CSR), to generate interactive components on the client with prerendering on the serverInteractive automatic rendering (IAR), to generate content using the server-side ASP.NET Core runtime at startup, and then switching to the .NET WebAssembly runtime on the client after the Blazor bundle is downloaded and the WebAssembly runtime activatesFor additional information regarding the Blazor render modes, check out the following article:
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes
Other valuable improvements include SignalR stateful reconnect, minimal APIs explicit binding to HTTP forms (using the [FromForm] attribute), better antiforgery capabilities, a more comprehensive AOT deployment model, and so on.
This concludes our journey through the recent history of ASP.NET. In the next section, we’ll move our focus to the Angular ecosystem, which experienced a rather similar turn of events.
If following in the footsteps of Microsoft and the .NET Foundation in recent years has not been an easy task, things were not going to get any better when we turned our eyes to the client-side web framework known as Angular. To understand what happened there, we have to go back 10 years to when JavaScript libraries such as jQuery and MooTools were dominating the client-side scene; the first client-side frameworks, such as Dojo, Backbone.js, and Knockout.js, were struggling to gain popularity and reach wide adoption; and stuff such as React and Vue.js didn’t even exist.
Truth be told, jQuery is still dominating the scene to a huge extent, at least according to BuiltWith (https://trends.builtwith.com/javascript/javascript-library) and w3Techs (https://w3techs.com/technologies/overview/javascript_library/all). However, despite being used by 74.1% of all websites, it’s definitely an option chosen less often by web developers than it was 10 years ago.
The story of AngularJS started in 2009 when Miško Hevery (now senior computer scientist and Agile coach at Google) and Adam Abrons (now director of engineering at Grand Rounds) were working on their side project, an end-to-end (E2E) web development tool that would have offered an online JSON storage service and also a client-side library to build web applications depending on it. To publish their project, they took the GetAngular.com hostname.
During that time, Hevery, who was already working at Google, was assigned to the Google Feedback project with two other developers. Together, they wrote more than 17,000 lines of code in 6 months, slowly sinking into a frustrating scenario of code bloat and testing issues. Given the situation, Hevery asked his manager to rewrite the application using GetAngular (the side project mentioned previously), betting that he could do that alone within 2 weeks. His manager accepted and Hevery lost the bet shortly thereafter, as the whole thing took him 3 weeks instead of 2; however, the new application had only 1,500 lines of code instead of 17,000. This was more than enough to get Google’s interest in the new framework, which was given the name AngularJS shortly thereafter.
To listen to the full story, take a look at the following Miško Hevery keynote speech at ng-conf 2014: https://www.youtube.com/watch?v=r1A1VR0ibIQ.
The first stable release of AngularJS (version 0.9.0, also known as dragon-breath) was released on GitHub in October 2010 under an MIT license; when AngularJS 1.0.0 (also known as temporal domination) came out in June 2012, the framework had already achieved huge popularity within the web development communities worldwide.
The reasons for such extraordinary success can hardly be summarized in a few words, but I’ll try to do that nonetheless by emphasizing some key selling points:
Dependency injection: AngularJS was the first client-side framework to implement it. This was undeniably a huge advantage over the competitors, including DOM-manipulating libraries such as jQuery. With AngularJS, developers could write loosely coupled and easily testable components, leaving the framework with the task of creating them, resolving their dependencies, and passing them to other components when requested.Directives: These can be described as markers on specific DOM items such as elements, attributes, and styles: a powerful feature that could be used to specify custom and reusable HTML-like elements and attributes that define data bindings and/or other specific behaviors of presentation components.Two-way data binding: The automatic synchronization of data between model and view components. When data in a model changes, the view reflects the change; when data in the view changes, the model is updated as well. This happens immediately and automatically, which makes sure that the model and the view are updated at all times.Single-page approach: AngularJS was the first framework to completely remove the need for page reloads. This provided great benefits on both the server side (fewer and smaller network requests) and client side (smoother transitions, a more responsive experience), and paved the way for the SPA pattern that would also be adopted by React, Vue.js, and the other runner-up frameworks later on.Cache-friendly: All the AngularJS magic was meant to happen on the client side, without any server-side effort to generate the UI/UX parts. For this very reason, all AngularJS websites could be cached anywhere and/or made available through a CDN.For a detailed list of AngularJS features, improvements, and bug fixes from 0.9.0 through 1.7.8, check out the following link:
AngularJS 1.x Changelog: https://github.com/angular/angular.js/blob/master/CHANGELOG.mdThe new release of AngularJS, released on September 14, 2016, and known as Angular 2, was a complete rewrite of the previous one, entirely based upon the new ECMAScript version 6 (officially ECMAScript 2015) specifications. Just like the ASP.NET Core rewrite, the revolution brought such a number of breaking changes at the architectural level and for HTTP pipeline handling, the app life cycle, and state management that porting the old code to the new one was nearly impossible. Despite keeping its former name, the new Angular version was a brand-new framework with little or nothing in common with the previous one.
The choice to not make Angular 2 backward-compatible with AngularJS clearly demonstrated the intention of the author’s team to adopt a completely new approach, not only in the code syntax but also in their way of thinking and designing the client app.
The new Angular was highly modular, component-based, and came with a new and improved dependency injection model and a whole lot of programming patterns its older cousin had never heard of.
Here’s a brief list of the most important improvements introduced with Angular 2:
Semantic versioning: Angular 2 is the first release to use semantic versioning, also known as SemVer: a universal way of versioning the various software releases to help developers track down what’s going on without having to dig into the changelog details. SemVer is based on three numbers – X.Y.Z, where X stands for a major version, Y stands for a minor version, and Z stands for a patch release. More specifically, the X number, representing the major version, gets incremented when incompatible API changes are made to stable APIs; the Y number, representing the minor version, gets incremented when backward-compatible functionality is added; and the Z number, representing a patch release, gets incremented when a backward-compatible bug is fixed. Such improvements can be easily underestimated, yet it’s a must-have for most modern software development scenarios where continuous delivery (CD) is paramount and new versions are released with great frequency.TypeScript