Home Web Development ASP.NET Core 8 and Angular - Sixth Edition

ASP.NET Core 8 and Angular - Sixth Edition

By Valerio De Sanctis
books-svg-icon Book
eBook $43.99 $29.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 $43.99 $29.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 Ready
About this book
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.
Publication date:
February 2024
Publisher
Packt
Pages
804
ISBN
9781805129936

 

Getting Ready

In this second chapter, we’ll switch from theory to practice: more specifically, we will choose the kind of web application that we want to build and see how we can do it in accordance with the expectations of a typical product owner.

In the second part of this chapter, we’ll start our development journey by setting up our local development environment and creating our first Angular and ASP.NET Core projects.

Here’s a full breakdown of the topics we’re going to cover:

  • A full-stack approach: The importance of being able to learn how to design, assemble, and deliver a complete product.
  • Multi-page applications (MPAs), single-page applications (SPAs), native web applications (NWAs), and progressive web applications (PWAs): Key features of and the most important differences between the various types of web applications, as well as how well ASP.NET and Angular could relate to each one of them.
  • A sample SPA project: What we’re going to do throughout this book.
  • Preparing the workspace: How to set up our workstation to achieve our first goal – implementing a simple Hello World boilerplate that will be further extended in the following chapters.

By the end of the chapter, we’ll have everything we need to start our full-stack development journey.

 

Technical requirements

In this chapter, we’re going to need all the technical requirements listed in the previous chapters, with no additional resources, libraries, or packages.

The code files for this chapter can be found here: https://github.com/PacktPublishing/ASP.NET-Core-8-and-Angular/tree/main/Chapter_02/HealthCheck.

 

A full-stack approach

Learning to use ASP.NET Core and Angular together means being able to work with both the front-end (client side) and back-end (server side) of a web application; to put it in other words, it means being able to design, assemble, and deliver a complete product.

Eventually, in order to do that, we’ll need to dig through the following:

  • Back-end programming
  • Front-end programming
  • UI styling and UX design
  • Database design, modeling, configuration, and administration
  • Web server configuration and administration
  • Web application deployment

At first glance, it can seem that this kind of approach goes against common sense; a single developer should not be allowed to do everything by themselves. Every developer knows that the back-end and the front-end require entirely different skills and experience, so why in the world should we do that?

Before answering this question, we should understand what we really mean when we say being able to. We don’t have to become experts on every single layer of the stack; no one expects us to. When we choose to embrace the full-stack approach, what we really need to do is raise our awareness level throughout the whole stack we’re working on; this means that we need to know how the back-end works, and how it can and will be connected to the front-end. We need to know how the data will be stored, retrieved, and then served through the client. We need to acknowledge the interactions we will need to layer out between the various components that our web application is made from, and we need to be aware of security concerns, authentication mechanisms, optimization strategies, load balancing techniques, and so on.

This doesn’t necessarily mean that we have to have strong skills in all these areas; as a matter of fact, we hardly ever will. Nonetheless, if we want to pursue a full-stack approach, we need to understand the meaning, role, and scope of all of them. Furthermore, we should be able to work our way through any of these fields whenever we need to.

 

MPAs, SPAs, PWAs, and NWAs

In order to demonstrate how ASP.NET and Angular can work together to their full extent, we couldn’t think of anything better than building some small SPA projects with most, if not all, PWA features. The reason for this choice is quite obvious: there is no better approach to demonstrate some of the best features they have to offer nowadays. We’ll have the chance to work with modern interfaces and patterns such as the HTML5 pushState API, webhooks, data-transport-based requests, dynamic web components, UI data bindings, and a stateless, AJAX-driven architecture capable of flawlessly encompassing all of these features. We’ll also make good use of some distinctive PWA features such as service workers and web manifest files.

The AJAX acronym stands for Asynchronous JavaScript And XML and is typically used when referring to a set of web development techniques to send and retrieve data from a server asynchronously. In practice, modern implementations of these techniques – such as Fetch API – utilize JSON instead of XML, thus making the term “AJAX” less precise to describe this type of interaction. Although that noun is still used nowadays for historical reasons, the term “XHR/Fetch” is a more correct way to properly describe these techniques.

If you don’t know the meaning of these definitions and acronyms, don’t worry, we are going to explore these concepts in the next couple of sections, which are dedicated to enumerating the most relevant features of the following types of web applications: MPAs, SPAs, PWAs, and NWAs. While we’re there, we’ll also try to figure out the most common product owner’s expectations for a typical web-based project.

Multi-page applications

Multi-page applications, also known as MPAs, are those web applications that work in a traditional way: each time the user asks for (or submits) data to the server, they render a new page that is sent back to the browser.

This is how all websites used to work during the first 20 years of the World Wide Web, and is still the most widely used approach nowadays due to a number of advantages that MPAs can still provide: excellent SEO performance, a fast and steady learning curve, the ability to manage and customize static and dynamic content, and a lot of great content management systems (CMSes), frameworks, and UI themes – such as WordPress, Joomla, and the like – that can be used to build them from the ground up in a few minutes.

However, MPAs also come with some significant cons: the required server-side roundtrips tend to make them quite expensive in terms of bandwidth; moreover, front-end and back-end development are often tightly coupled, thus making them harder to maintain and update. Luckily enough, most of these issues have been mitigated throughout the years, thanks to various browser features and technology improvements such as CDN, server-side caching, XHR/Fetch requests, and so on. At the same time, such techniques add more complexity to the development and deployment phases; that is, unless we choose to rely upon one of the CMS platforms that we talked about early on, thus giving up on most of the coding aspects – with all that that implies.

Single-page applications

To put it briefly, an SPA is a web-based application that tries to provide the same user experience as a desktop application. If we consider the fact that all SPAs are still served through a web server and thus accessed by web browsers, just like any other standard website, we can easily understand how that desired outcome can only be achieved by changing some of the default patterns commonly used in web development, such as resource loading, DOM management, and UI navigation. In a good SPA, both content and resources – HTML, JavaScript, CSS, and so on – are either retrieved within a single page load or are dynamically fetched when needed. This also means that the page doesn’t reload or refresh; it just changes and adapts in response to user actions, performing the required server-side calls behind the scenes.

These are some of the key features provided by a competitive SPA nowadays:

  • No server-side round trips: A competitive SPA can redraw any part of the client UI without requiring a full server-side round trip to retrieve a full HTML page. This is mostly achieved by implementing the separation of concerns (SOC) design principle, which means that the data source, the business logic, and the presentation layer will be separated.
  • Efficient routing: A competitive SPA is able to keep track of the user’s current state and location during its whole navigation experience using organized, JavaScript-based routers. We’ll talk more about that in the upcoming chapters when we introduce the concepts of server-side and client-side routing.
  • Performance and flexibility: A competitive SPA usually transfers all of its UI to the client, thanks to its JavaScript SDK of choice (Angular, jQuery, Bootstrap, and so on). This is often good for network performance as increasing client-side rendering and offline processing reduces the UI impact over the network. However, the real deal brought by this approach is the flexibility granted to the UI as the developer will be able to completely rewrite the application’s front-end with little or no impact on the server, aside from a few of the static resource files.

This list can easily grow, as these are only some of the major advantages of a properly designed, competitive SPA. These aspects play a major role nowadays, as many business websites and services are switching from their traditional MPA mindset to fully committed or hybrid SPA-based approaches.

Progressive web applications

In 2015, another web development pattern pushed its way into the light when Frances Berriman (a British freelance designer) and Alex Russel (a Google Chrome engineer) used the term PWAs for the first time to refer to those web applications that could take advantage of a couple of new important features supported by modern browsers: service workers and web manifest files. These two important improvements could be successfully used to deliver some functionalities usually only available on mobile apps – push notifications, offline mode, permission-based hardware access, and so on – using standard web-based development tools such as HTML, CSS, and JavaScript.

The rise of PWAs began on March 19, 2018, when Apple implemented support for service workers in Safari 11.1. Since that date, PWAs have been widely adopted throughout the industry thanks to their undeniable advantages over their “non-progressive” counterparts: faster load times, smaller application sizes, higher audience engagement, and so on.

Here are the main technical features of a PWA (according to Google):

  • Progressive: Works for every user, regardless of browser choice, using progressive enhancement principles
  • Responsive: Fits any form factor: desktop, mobile, tablet, or forms yet to emerge
  • Connectivity independent: Service workers allow offline use, or use on low-quality networks
  • App-like: Feels like an app to the user with app-style interactions and navigation
  • Fresh: Always up to date due to the service worker update process
  • Safe: Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with
  • Discoverable: Identifiable as an application by a web manifest (manifest.json) file, and a registered service worker, and discoverable by search engines
  • Re-engageable: The ability to use push notifications to maintain engagement with the user
  • Installable: Provides home screen icons without the use of an app store
  • Linkable: Can easily be shared via a URL and does not require complex installation

However, their technical baseline criteria can be restricted to the following subset:

  • HTTPS: They must be served from a secure origin, which means over TLS with green padlock displays (no active mixed content)
  • Minimal offline mode: They must be able to start even if the device is not connected to the web, with limited functions or at least displaying a custom offline page
  • Service workers: They have to register a service worker with a fetch event handler (which is required for minimal offline support, as explained previously)
  • Web manifest file: They need to reference a valid manifest.json file with at least four key properties (name, short_name, start_url, and display) and a minimum set of required icons

For those interested in reading about this directly from the source, here’s the original link from the Google Developers website:

https://developers.google.com/web/progressive-web-apps/

In addition, here are two follow-up posts from Alex Russell’s Infrequently Noted blog:

https://infrequently.org/2015/06/progressive-apps-escaping-tabs-without-losing-our-soul/

https://infrequently.org/2016/09/what-exactly-makes-something-a-progressive-web-app/

For those who don’t know, Alex Russell has worked as a senior staff software engineer at Google since December 2008.

Although they have some similarities, PWAs and SPAs are two different concepts, have different requirements, and differ in many important aspects. As we can see, none of the PWA requirements mentioned previously refer to SPAs or server-side round trips. A PWA can work within a single HTML page and XHR/Fetch requests (thus also being an SPA), but it could also request other server-rendered (or static) pages and/or perform standard HTTP GET or POST requests, much like an MPA. It’s also the opposite: any SPA can implement any single PWA technical criteria, depending on the product owner’s requirements (more on that later), the server-side and client-side frameworks adopted, and the developer’s ultimate goal.

Native web applications

The first good definition of native web applications (also known as NWAs) available on the web can arguably be found in Sam Johnston’s blog post written on January 16, 2009, which went like this:

"A Native Web Application (NWA) is a web application which is 100% supported out of the box by recent standards-compliant web browsers."

A similar approach was used 6 years later (January 22, 2015) by Henrik Joreteg to describe the defining feature of NWAs:

”The thing these apps all have in common is that they all depend on the native web technologies: HTML, CSS, and JavaScript (arguably, you could add WebGL to that list).”

These definitions help us to understand that we’re dealing with a rather generic term that encompasses SPAs, MPAs, and even PWAs – since they all depend on native web technologies that are supported out of the box by all recent browsers; however, due to the emphasis given to the recent keyword and the existence of the more specific web application types, the term NWA is mostly used to identify those web applications that, although being built using modern web-based technologies, cannot be classified as MPAs, SPAs, or PWAs because they tend to adopt a hybrid approach.

Since we’re going to use Angular, which is all about developing SPAs and has also shipped with a strong and steady service worker implementation since version 5, we are fully entitled to take advantage of the best of both worlds. For this very reason, we’re going to use service workers – along with the benefits of increased reliability and performance they provide – whenever we need to, all while keeping a solid SPA approach. Furthermore, we’re definitely going to implement some strategic HTTP round trips (and/or other redirect-based techniques) whenever we can profitably use a microservice to lift off some workload from our app, just like any good NWA is meant to do.

Are all these features able to respond to modern market needs? Let’s try to find it out.

Product owner expectations

One of the most interesting, yet underrated, concepts brought out by many modern Agile software development frameworks, such as Scrum, is the importance given to the meanings and definitions of roles. Among these roles, there’s nothing as important as the product owner, also known as the customer in the Extreme Programming methodology, or customer representative elsewhere. They’re the ones who bring to the development table the expectations we’ll struggle to satisfy. They will tell us what’s most important to deliver and when they will prioritize our work based on its manifest business value rather than its underlying architectural value. They’ll be empowered by management to make decisions and make tough calls, which is sometimes great, sometimes not.

This will often have a big impact on our development schedule. To cut it short, they’re the ones in charge of the project; that’s why, in order to deliver a web application matching their expectations, we’ll need to understand their vision and feel it as if it were our own.

This is always true, even if the project’s product owner is our dad, wife, or best friend: that’s how it works.

Now that we have made that clear, let’s take a look at some of the most common product owner expectations for a typical web-based SPA project. We ought to see whether the choice of using ASP.NET and Angular will be good enough to fulfill each one of them, as follows:

  • Early release(s): No matter what we’re selling, the customer will always want to see what they’re buying. For example, if we plan to use an Agile development framework such as Scrum, we’ll have to release a potentially shippable product at the end of each sprint, or if we are looking to adopt a Waterfall-based approach, we’re going to have milestones. One thing is for sure, the best thing we can do in order to efficiently organize our development efforts will be to adopt an iterative and/or modular-oriented approach. ASP.NET and Angular, along with the strong separation of concerns granted by their underlying MVC- or MVVM-based patterns, will gracefully push us into the mindset needed to do just that.
  • GUI over back-end: We’ll often be asked to work on the GUI and front-end functionalities because they will be the only things that are viewable and measurable for the customer. This basically means that we’ll have to mock the data model and start working on the front-end as soon as possible, delaying the back-end implementation as much (and as long) as we can. Note that this kind of approach is not necessarily bad; we just won’t do that just to satisfy the product owner’s expectations.

    On the contrary, the choice of using ASP.NET along with Angular will grant us the chance to easily decouple the presentation layer and the data layer, implementing the first and mocking the latter, which is a great thing to do. We’ll be able to see where we’re going before wasting valuable time or being forced to make potentially wrong decisions. ASP.NET’s web API interface will provide the proper tools to do that by allowing us to create a sample web application skeleton in a matter of seconds using the controller templates available within Visual Studio and in-memory data contexts powered by Entity Framework Core, which we’ll be able to access using Entity models and code first. As soon as we do that, we’ll be able to switch to GUI design using the Angular presentation layer toolbox as much as we want until we reach the desired results. Once we’re satisfied, we’ll just need to properly implement the Web API controller interfaces and hook up the actual data.

  • Fast completion: None of the preceding things will work unless we also manage to get everything done in a reasonable time span. This is one of the key reasons to choose to adopt a server-side framework and a client-side framework that work together with ease. ASP.NET and Angular are the tools of choice, not only because they’re both built on solid, consistent ground, but also because they’re meant to do precisely that – get the job done on their respective sides and provide a usable interface to the other partner.
  • Adaptability: As stated by the Agile Manifesto, being able to respond to change requests is more important than following a plan. This is especially true in software development where we can even claim that anything that cannot handle change is a failed project. That’s another great reason to embrace the separation of concerns enforced by our two frameworks of choice, as this grants the developer the ability to manage—and even welcome, to some extent—most of the layout or structural changes that will be expected during the development phase.

A few lines ago, we mentioned Scrum, which is one of the most popular Agile software development frameworks out there. Those who don’t know it yet should definitely take a look at what it can offer to any results-driven team leader and/or project manager. Here’s a good place to start:

https://en.wikipedia.org/wiki/Scrum_(software_development)

For those who are curious about the Waterfall model, here’s a good place to learn more about it:

https://en.wikipedia.org/wiki/Waterfall_model

That’s about it. Note that we didn’t cover everything here as it would be impossible without the context of an actual assignment. We just tried to give an extensive answer to the following general question: if we were to build an SPA and/or a PWA, would ASP.NET and Angular be an appropriate choice? The answer is undoubtedly yes, especially when used together.

Does this mean that we’re done already? Not a chance, as we have no intention of taking this assumption for granted. Conversely, it’s time for us to demonstrate this by ceasing to speak in general terms and starting to put things in motion. That’s precisely what we’re going to do in the next section: prepare, build, and test an example SPA project.

 

An example SPA project

What we need now is to conceive a suitable test case scenario similar to the ones we will eventually have to deal with – an example SPA project with all the core aspects we would expect from a potentially shippable product.

In order to do this, the first thing we need to do is to become our own customer for a minute and come up with an idea, a vision to share with our other self. We’ll then be able to put our developer shoes back on and split our abstract plan into a list of items we’ll need to implement; these items will be the core requirements of our project. Finally, we’ll set up our workstation by getting the required packages, adding the resource files, and configuring both the ASP.NET and Angular frameworks in the Visual Studio IDE.

Not your usual Hello World!

The code we’re going to write within this book won’t be just a shallow demonstration of full-stack development concepts; we won’t throw some working code here and there and expect you to connect the dots. Our objective is to create solid, realistic web applications – with server-side web APIs and client-side UIs – using the frameworks we’ve chosen, and we’re also going to do that following the current development best practices.

Each chapter will be dedicated to a single core aspect. If you feel like you already know your way there, feel free to skip to the next one. Conversely, if you’re willing to follow us through the whole loop, you’ll have a great journey through the most useful aspects of ASP.NET and Angular, as well as how they can work together to deliver the most common and useful web development tasks, from the most trivial ones to the more complex beasts. It’s an investment that will pay dividends as it will leave you with a maintainable, extensible, and well-structured project, plus the knowledge needed to build your own. The following chapters will guide us through this journey. During the trip, we’ll also learn how to take care of some important high-level aspects, such as SEO, security, performance issues, best coding practices, and deployment, as they will become very important if/when our applications are eventually published in a production environment.

To avoid making things too boring, we’ll try to pick enjoyable themes and scenarios that will also have some usefulness in the real world: to better understand what we mean – no spoilers here – you’ll just have to keep reading.

 

Preparing the workspace

The first thing we have to do is set up our workstation; it won’t be difficult because we only need a small set of essential tools. These include Visual Studio 2022, an updated Node.js runtime, a development web server (such as the built-in IIS Express), and a decent source code control system, such as Git. We will take the latter for granted as we most likely already have it up and running.

In the unlikely case you don’t, you should really make amends before moving on! Stop reading, go to www.github.com, www.bitbucket.com, or whichever online source code management (SCM) service you like the most, create a free account, and spend some time learning how to effectively use these tools; you won’t regret it, that’s for sure.

In the next sections, we’ll set up the web application project, install or upgrade the packages and libraries, and build and eventually test the result of our work. However, before doing that, we’re going to spend a couple of minutes understanding a very important concept that is required to properly use this book without getting (emotionally) hurt, at least in my opinion.

Disclaimer — do (not) try this at home

There’s something very important that we need to understand before proceeding. If you’re a seasoned web developer, you will most likely know about it already; however, since this book is for (almost) everyone, I feel like it’s very important to deal with this matter as soon as possible.

This book will make extensive use of a number of different programming tools, external components, third-party libraries, and so on. Most of them (such as TypeScript, npm, NuGet, most .NET frameworks/packages/runtimes, and so on) are shipped together with Visual Studio 2022, while others (such as Angular, its required JavaScript dependencies, and other third-party server-side and client-side packages) will be fetched from their official repositories. These things are meant to work together in a 100% compatible fashion; however, they are all subject to changes and updates during the inevitable course of time. As time passes by, the chance that these updates might affect the way they interact with each other, and the project’s health, will increase.

The broken code myth

In an attempt to minimize the chances of broken code occurring, this book will always work with fixed versions/builds of any third-party component that can be handled using the configuration files. However, some of them, such as Visual Studio and/or .NET SDK updates, might be out of that scope and might wreak havoc on the project. The source code might cease to work, or Visual Studio could suddenly be unable to properly compile it.

When something like that happens, a less experienced person will always be tempted to put the blame on the book itself. Some of them may even start thinking something like this: There are a lot of compile errors, hence the source code must be broken!

Alternatively, they may think like this: The code sample doesn’t work: the author must have rushed things here and there and forgot to test what he was writing.

It goes without saying that such hypotheses are rarely true, especially considering the amount of time that the authors, editors, and technical reviewers of these books spend in writing, testing, and refining the source code before building it up, making it available on GitHub, and often even publishing working instances of the resulting applications to worldwide public websites.

The GitHub repository for this book can be found here:

https://github.com/PacktPublishing/ASP.NET-Core-8-and-Angular

It contains a Visual Studio solution file for each chapter containing source code (Chapter_02.sln, Chapter_03.sln, and so on), as well as an additional solution file (All_Chapters.sln) containing the source code for all the chapters.

Any experienced developer will easily understand that most of these things couldn’t even be done if there was some broken code somewhere; there’s no way this book could even attempt to hit the shelves without coming with a 100% working source code, except for a few possible minor typos that will quickly be reported to the publisher and thus fixed within the GitHub repository in a short while. In the unlikely case that it looks like it doesn’t, such as raising unexpected compile errors, the novice developer should spend a reasonable amount of time trying to understand the root cause.

Here’s a list of questions they should try to answer before anything else:

  • Am I using the same development framework, third-party libraries, versions, and builds adopted by the book?
  • If I updated something because I felt like I needed to, am I aware of the changes that might affect the source code? Did I read the relevant changelogs? Have I spent a reasonable amount of time looking around for breaking changes and/or known issues that could have had an impact on the source code?
  • Is the book’s GitHub repository also affected by this issue? Did I try to compare it with my own code, possibly replacing mine?

If the answer to any of these questions is No, then there’s a good chance that the problem is not ascribable to this book.

Stay hungry, stay foolish, yet be responsible as well

Don’t get me wrong: if you want to use a newer version of Visual Studio, update your TypeScript compiler, or upgrade any third-party library, you are definitely encouraged to do that. This is nothing less than the main scope of this book – making you fully aware of what you’re doing and capable of, way beyond the given code samples.

However, if you feel you’re ready to do that, you will also have to adapt the code accordingly; most of the time, we’re talking about trivial stuff, especially these days when you can Google the issue and/or get the solution on Stack Overflow. Have they changed the name of a property or method? Then you need to load the new spelling. Have they moved the class somewhere else? Then you need to find the new namespace and change it accordingly, and so on.

That’s about it – nothing more, nothing less. The code reflects the passage of time; the developer just needs to keep up with the flow, performing minimum changes to it when required. You can’t possibly get lost and blame someone other than yourself if you update your environment and fail to acknowledge that you have to change a bunch of code lines to make it work again.

Am I implying that the author is not responsible for the source code of this book? It’s the exact opposite; the author is always responsible. They’re supposed to do their best to fix all the reported compatibility issues while keeping the GitHub repository updated. However, you should also have your own level of responsibility; more specifically, you should understand how things work for any development book and the inevitable impact of the passage of time on any given source code. No matter how hard the author works to maintain it, the patches will never be fast or comprehensive enough to make these lines of code always work in any given scenario. That’s why the most important thing you need to understand – even before the book’s topics – is the most valuable concept in modern software development: being able to efficiently deal with the inevitable changes that will always occur. Whoever refuses to understand that is doomed; there’s no way around it.

Now that we’ve clarified these aspects, let’s get back to work.

Setting up the project(s)

Assuming we have already installed Visual Studio 2022 and Node.js (as described in Chapter 1, Introducing ASP.NET and Angular), here’s what we need to do:

  1. Download and install the .NET 8 SDK.
  2. Check that the .NET CLI will use that SDK version.
  3. Install the Angular CLI.
  4. Create a new .NET and Angular project.
  5. Check out the newly created project within Visual Studio.
  6. Update all the packages and libraries to our chosen versions.

Let’s get to work.

Installing the .NET 8 SDK

The .NET 8 SDK can be downloaded from either the official Microsoft URL (https://dotnet.microsoft.com/download/dotnet/8.0) or from the GitHub official release page (https://github.com/dotnet/core/tree/master/release-notes/8.0).

The installation is very straightforward – just follow the wizard until the end to get the job done, as follows:

A screenshot of a computer

Description automatically generated

Figure 2.1: .NET SDK 8.0.100 installer

The whole installation process shouldn’t take more than a couple of minutes.

Checking the SDK version

Once the .NET SDK has been installed, we need to confirm that the new SDK PATH has been properly set and/or that the .NET CLI will actually use it. The fastest way to check that is by opening Command Prompt and typing the following:

> dotnet --version

Be sure that the .NET CLI executes without issue and that the version number is the same as we installed a moment ago.

If the prompt is unable to execute the command, go to Control Panel | System | Advanced System Settings | Environment Variables and check that the C:\Program Files\dotnet\ folder is present within the PATH environment variable; manually add it if needed.

Installing Node.js and the Angular CLI

The next thing we must do is to install the Angular Command-Line Interface – better known as the Angular CLI. In order to do that, we have to install Node.js, so that we can access npm and use it to get the official Angular packages.

If you’re on Windows, we strongly suggest installing Node.js using nvm for Windows – a neat Node.js version manager for the Windows system. The tool can be downloaded from the following URL: https://github.com/coreybutler/nvm-windows/releases.

Once Node.js has been installed, the Angular CLI can be installed using the following command:

npm install -g @angular/cli@17.0.3

After doing that, you should be able to type ng -version and get the Angular CLI ASCII logo containing the installed packages version. If that’s not the case, you might have to add the Node.js and/or npm /bin/ folder to your PATH environment variable.

After our frameworks and all the prerequisites have been installed, we can restart your computer (to ensure that everything will be loaded on startup) and go ahead.

Creating the Angular and ASP.NET Core project

Now we can create our first .NET and Angular project – in other words, our first app.

Visual Studio 2022 gives us two built-in options for doing this:

  • Use the Standalone TypeScript Angular Template together with the ASP.NET Core Web API template, an approach introduced with the initial release of Visual Studio 2022 that allows to keep the front-end Angular app and the back-end ASP.NET Core API in two separate projects, although fully able to interoperate with each other.
  • Use the new Angular and ASP.NET Core Template, a new approach introduced with Visual Studio 2022 v17.8 that allows to achieve the same results as the standalone template, but with less configuration effort.

The two approaches are very similar, and both of them are viable enough since they enforce the good practice of decoupling the front-end and the back-end architecture (as well as codebases), which is a pivotal concept when dealing with SPAs: being able to deal with this “multi-project approach” will definitely help the reader to better understand the distinct underlying logic of both frameworks, not only during development but also when we’ll have to eventually publish and deploy our app(s).

Furthermore, both of them will generate the boilerplate code of the front-end app using the Angular CLI version installed on the computer, which is great, because it means that our source code will be fully compatible (and up to date) with the Angular version that we have installed.

That said, for the purpose of this book we’re going to use the new Angular and ASP.NET Core Template, which will allow us to achieve optimal results with less effort.

Creating the Angular project

Let’s start with the front-end Angular project, which will also provide the name for our Visual Studio 2022 solution.

For those who don’t know the Visual Studio naming conventions, a solution is basically a collection of one or multiple projects: in our multi-project approach we’ll end up having two projects (the front-end Angular App and the back-end ASP.NET Core Web API) within a single solution.

Launch Visual Studio, then click on the Create a new project button: use the search textbox near the top of the window to look for the Angular and ASP.NET Core project template, just like shown in the following screenshot:

Immagine che contiene testo, schermata, software, schermo

Descrizione generata automaticamente

Figure 2.2: Creating a new Standalone TypeScript Angular template

Select that template and click Next to access the Configure your new project screen. In the following screenshot, fill the form with the following values:

  • Solution name: HealthCheck
  • Location: C:\Projects\
  • Create in new folder: Yes (checked)

    There’s a good reason for calling our project HealthCheck, as we’re going to see in a short while (no spoilers, remember?).

Immagine che contiene testo, schermata, schermo, software

Descrizione generata automaticamente

Figure 2.3: Standalone TypeScript Angular Project configuration wizard

It goes without saying that these are only suggested choices. However, in this book we’re going to use these names – which will impact our source code in terms of class names, namespaces, and so on – and \Projects\ as our root folder. Inexperienced developers are strongly advised to use the same names and folder.

Choosing a root-level folder with a short name is also advisable to avoid possible errors and/or issues related to path names being too long: Windows 10 has a 260-character limit that can create some issues with some deeply nested npm packages.

When done, click the Next button again to access the third and last section of the wizard: Additional information.

Here, we need to be sure to choose the .NET 8 Framework, then leave the default options as they already are: Configure for HTTPS: checked, Enable OpenAPI support: checked, Do not use top-level statements: unchecked, Use controllers: checked, as shown in the following screenshot.

Immagine che contiene testo, schermata, schermo, software

Descrizione generata automaticamente

Figure 2.4: ASP.NET Core Web API template configuration wizard

Once this is done, hit Create to complete the wizard. As soon as we do that, Visual Studio will start to create and prepare our new project(s): when everything is set and done, the development GUI will appear with the new solution’s file tree clearly visible in the Solution Explorer window, as shown in the following screenshot:

Immagine che contiene testo, schermata, software, computer

Descrizione generata automaticamente

Figure 2.5: Our HealthCheck solution, featuring two distinct projects for client and server

As we can easily expect, our solution is composed of two distinct projects:

  • The healthcheck.client project, for the Angular app
  • The HealthCheck.Server project, for the ASP.NET Core Web API

Now we have the front-end project and the back-end project ready within the same solution: we just need a few tweaks to their configuration settings to ensure they will be executed together as we want them to do.

Setting up the HTTP and HTTPS ports

From Solution Explorer, open the HealthCheck.Server project node (the ASP.NET one), then open the /Properties/ folder and double-click the launchSettings.json file to open it in the text editor.

Once you’re there, perform the following changes:

  • Set all the "launchBrowser" settings to false.
  • Replace the random-generated HTTP and HTTPS ports with fixed values. We’re going to use 40080 for HTTP and 40443 for HTTPS.

The reason to use fixed ports is that we’ll have to deal with some framework features (such as internal proxies) that require fixed endpoints. In the unlikely event that these ports end up being busy and/or cannot be used, feel free to change them: just be sure to apply the same changes throughout the whole book to avoid getting HTTP 404 errors.

Here’s what our launchSettings.json file should look like after these changes (updated lines are highlighted):

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:40080",
      "sslPort": 40443
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "launchUrl": "swagger",
      "applicationUrl": "http://localhost:40080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:40443;http://localhost:40080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_HOSTINGSTARTUPASSEMBLIES": "Microsoft.AspNetCore.SpaProxy"
      }
    }
  }
}

Now we just need to tell Visual Studio how to properly run our projects.

Setting the startup project(s)

Since we are dealing with two projects that need to work together, we need to make good use of one of the most important, yet less-known features introduced with the latest versions of Visual Studio, at least for SPAs: the ability to set up multiple startup projects.

It’s worth noting that, in the latest versions of Visual Studio 2022, the following settings should be already OK, but it’s better to check that this is the case.

From Solution Explorer, right-click on the HealthCheck solution (the top-level node) and select Configure Startup Projects, then perform the following steps:

  1. In the modal window that opens, ensure that the startup project radio button is set to Multiple startup projects, and that the Action column value is set to Start for both of our projects.
  2. Ensure that the HealthCheck.Server (ASP.NET) project is placed above the healthcheck.client (Angular) project, so that it will be launched first. If that’s not the case, operate with the two arrows to the right to achieve that result.

Here’s what the Multiple startup project settings should look like after these changes:

Immagine che contiene testo, schermata, schermo, software

Descrizione generata automaticamente

Figure 2.6: Solution ‘HealthCheck’ startup project settings window

Once this is done, we can move to the next (and last) step. Remember when we said that we would be dealing with fixed endpoints? Here’s the first one we need to take care of.

From the HealthCheck project, open the /src/proxy.conf.js file, which is the configuration file for the proxy that will be used by the Angular development server to reach our ASP.NET API project URLs when running our projects in Debug mode. Don’t worry about these concepts for now; we’ll explain them in a short while. For the time being, we just need to ensure that the proxy will route the API requests to the correct URL, including the HTTPS port.

For that reason, change the target URL to match the fixed HTTPS port that we’ve configured in the ASP.NET Core API project, which should be 40433 (unless we chose a different one):

const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
    ],
    target: "https://localhost:40443",
    secure: false
  }
]
module.exports = PROXY_CONFIG;

Let’s take the chance to choose a fixed HTTPS port for the Angular development server as well.

Open the /.vscode/launch.json file and change the default HTTPS port to 4200, as shown in the following highlighted code:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "edge",
      "request": "launch",
      "name": "localhost (Edge)",
      "url": "https://localhost:4200",
      "webRoot": "${workspaceFolder}"
    }
    {
      "type": "chrome",
      "request": "launch",
      "name": "localhost (Chrome)",
      "url": "https://localhost:4200",
      "webRoot": "${workspaceFolder}"
    },
  ]
}

IMPORTANT: Your launch.json file might be different if you have Chrome and/or MS Edge installed. Just keep the configuration blocks for the browser you have on your system and plan to use to debug your app and remove (or avoid adding) the others, otherwise your project will crash on startup. In this book, we’re going to use Chrome and MS Edge, hence we’ll keep the file as it is.

Now we’re finally ready to launch our project(s) and see how well they work together: this is what the next section is all about.

Performing a test run

The best way to see if our multi-project is working as expected is to perform a quick test run by launching our projects in Debug mode. To do that, hit the Visual Studio Start button or the F5 key to start downloading the required npm dependencies, compiling, and eventually running our app.

After a few seconds, we’ll be asked to trust a self-signed certificate that ASP.NET Core will generate to allow our app to be served through HTTPS (as shown in the following screenshot). Let’s just click Yes to continue.

Figure 2.7: Trust ASP.NET Core SSL Certificate popup

If we don’t want to have to authorize the ASP.NET Core self-signed SSL certificates, we can flag the Don’t ask me again checkbox right before hitting Yes.

Right after that, Visual Studio will launch three separate processes:

  • The ASP.NET Core Server, a web server that will serve the server-side APIs. This web server will be Kestrel (the default) or IIS Express, depending on the project configuration. Either of them will work for our purposes since we’ve wisely configured both to use the same fixed endpoints and HTTP/HTTPS ports:
Immagine che contiene testo, schermata, software, multimediale

Descrizione generata automaticamente

Figure 2.8: Kestrel web server for the ASP.NET Core Web API project

  • The Angular Live Development Server, a console application acting as a web server that will host our Angular application’s files using the ng serve command from the Angular CLI:
Immagine che contiene testo, schermata, software, schermo

Descrizione generata automaticamente

Figure 2.9 Angular Live Development Server for the Standalone TypeScript Angular project

  • Our favorite web browser, such as MS Edge, Mozilla Firefox, or Google Chrome (we’re going to use MS Edge from now on), which will interact with the Angular Live Development Server through the fixed HTTPS endpoint we configured a while ago:
Immagine che contiene testo, schermata, schermo, software

Descrizione generata automaticamente

Figure 2.10: MS Edge web browser for the Standalone TypeScript Angular project

The page we’re going to see in the web browser shows a basic Angular component performing a simple data fetching retrieval task from the ASP.NET Core Web API project: a tiny, yet good (and fully working) example of what we’ll be doing from now on.

What we just did was an excellent consistency check to ensure that our development system is properly configured. If we see the page shown in the preceding screenshot, it means that we’re ready to move on.

Troubleshooting

In the unlikely case we don’t, it probably means that we’re either missing something or that we’ve got some conflicting software preventing Visual Studio and/or the underlying .NET and Angular CLIs from properly compiling the project. To fix that, we can try to do the following:

  • Uninstall/reinstall Node.js, as we possibly have an outdated version installed.
  • Uninstall/reinstall Visual Studio, as our current installation might be broken or corrupted. The .NET SDK should come shipped with it already; however, we can try reinstalling it as well.

If everything still fails, we can try to install Visual Studio and the previously mentioned packages in a clean environment (either a physical system or a VM) to overcome any possible issues related to our current operating system configuration.

If none of these attempts work, the best thing we can do is to ask for specific support on the .NET community forums at https://forums.asp.net/default.aspx/7?General+ASP+NET.

Architecture overview

Before moving on to the next chapter, let’s take a couple more minutes to fully understand the underlying logic behind the development environment that we’ve just built.

We’ve already seen that when Visual Studio starts our projects in the development environment, three processes are launched: the standalone Angular project (healthcheck.client), the ASP.NET Core Web API (HealthCheck.Server), and the web browser that will interact with them.

Here’s a simple diagram that summarizes how these three processes work together and interact with each other:

Figure 2.11: healthcheck.client (front-end) and HealthCheck.Server (back-end) interaction in the development setup

As we can see from the previous diagram, the web browser will call the Angular Live Development Server (which listens to HTTPS port 4200), which will deal with them in the following way:

  • Directly serve all the requests for the Angular pages and static resources.
  • Proxy all the API requests to the Kestrel web server hosting the ASP.NET Core Web API (which listens to the HTTPS port 40443).

It’s important to understand that the Angular Live Development Server is only meant for local development, where it will allow the use of most debug tools and greatly speed up the coding experience with features such as hot reload. Whenever we want to deploy our app(s) in production, or in any environment other than local development, we’re going to build our app into production bundles and deploy them to a web server (or a CDN) that will basically take its place in the preceding diagram. We’ll talk about all this extensively in Chapter 15, Windows, Linux, and Azure Deployment, when we’ll learn how to publish our apps.

 

Summary

So far, so good; we’ve just set up a working skeleton of what’s about to come. Before moving on, let’s do a quick recap of what we just did (and learned) in this chapter.

First of all, we learned the differences between the various approaches that can be adopted to create web apps nowadays: SPAs, MPAs, and PWAs. We also explained that since we’ll be using .NET and Angular, we’ll stick to the SPA approach, but we’ll also implement most PWA features, such as a service worker and a web manifest file. In an attempt to reproduce a realistic production-case scenario, we also went through the most common SPA features, first from a technical point of view, and then putting ourselves in the shoes of a typical product owner while trying to enumerate their expectations.

Last, but not least, we learned how to properly set up our development environment; we chose to do that using the latest Angular SPA template shipped with the .NET SDK, thus adopting the standard ASP.NET Core/.NET 8 approach. Then, we used the built-in Visual Studio Angular and ASP.NET Core project template to create our healthcheck.client (front-end) and HealthCheck.Server (back-end) projects, configured them to be able to work together, and tested the overall result to ensure that everything was working properly. Finally, we spent some valuable time to fully understand how the development architecture that we’ve just built works.

In the next chapter, Chapter 3, Looking Around, we’ll take an extensive look at the app we just created to properly understand how the .NET back-end and the Angular front-end perform their respective tasks and what they can do together.

 

Suggested topics

For further information, we recommend the following topics: Single-Page Application (SPA), Progressive Web Application (PWA), Native Web Application (NWA), Multi-Page Application (MPA), Scrum, Agile Manifesto, ASP.NET Web API, Angular CLI, Node.js, npm, nvm for Windows, Visual Studio 2022, and Visual Studio project templates.

 

References

Learn more on Discord

Join our community’s Discord space for discussions with the author and other readers:

https://packt.link/aspdotnet8angular

About the Author
  • Valerio De Sanctis

    Valerio De Sanctis is a skilled IT professional with 20 years of experience in lead programming, web-based development, and project management using ASP.NET, PHP, Java, and JS-based frameworks. He currently holds the position of CTO for several top-tier companies. He is a Microsoft Most Valuable Professional (MVP) for Developer Technologies and the author of many best-selling books on back-end and front-end web development.

    Browse publications by this author
ASP.NET Core 8 and Angular - Sixth Edition
Unlock this book and the full library FREE for 7 days
Start now