36,59 €
Build modern, scalable, and cloud-ready single-page applications using ASP.NET Core, React, TypeScript, and Azure
Key Features
Book Description
Microsoft's ASP.NET Core is a robust and high-performing cross-platform web API framework, and Facebook's React uses declarative JavaScript to drive a rich, interactive user experience on the client-side web. Together, they can be used to build full stack apps with enhanced security and scalability at each layer.
This book will start by taking you through React and TypeScript components to build an intuitive single-page application. You'll understand how to design scalable REST APIs that can integrate with a React-based frontend. You'll get to grips with the latest features, popular patterns, and tools available in the React ecosystem, including function-based components, React Router, and Redux. The book shows how you can use TypeScript along with React to make the frontend robust and maintainable. You'll then cover important .NET Core features such as API controllers, attribute routing, and model binding to help you build a sturdy backend. Additionally, you'll explore API security with ASP.NET Core identity and authorization policies, and write reliable unit tests using both .NET Core and React before you deploy your app to the Azure cloud.
By the end of the book, you'll have gained all the knowledge you need to enhance your C# and JavaScript skills and build full stack, production-ready applications with ASP.NET Core and React.
What you will learn
Who this book is for
If you're a web developer looking to build solid full-stack web applications with .NET Core and React, this book is for you. Although this book does not assume any knowledge of React, you're expected to have a basic understanding of .NET Core.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 517
Veröffentlichungsjahr: 2019
Copyright © 2019 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.
Commissioning Editor:Pavan RamchandaniAcquisition Editor:Reshma RamanContent Development Editor: Divya VijayanSenior Editor: Mohammed Yusuf ImaratwaleTechnical Editor:Jane DsouzaCopy Editor: Safis EditingProject Coordinator:Manthan PatelProofreader: Safis EditingIndexer:Rekha NairProduction Designer:Jyoti Chauhan
First published: December 2019
Production reference: 1261219
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78995-022-9
www.packt.com
I'd like to thank Sarah, Ellie-Jayne, and Lily-Rose for all the encouragement and support they've given me while writing this book. A special thanks to everyone in the Packt editorial team for their hard work and great feedback, especially Arun Nadar, Divya Vijayan, and Jane D'souza.
Packt.com
Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Fully searchable for easy access to vital information
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Carl Rippon has been involved in the software industry for over 20 years, developing a complex line of business applications across various sectors. He has spent the last 8 years building single-page applications using a wide range of JavaScript technologies, including Angular, ReactJS, and TypeScript. Carl has written over 100 blog posts on various technologies.
Carlo Wahlstedt is a Jesus Follower, family man, and technologist. The latter leading to a diverse interest in anything technology can affect. Name a technology and Carlo as tried it, has it on his list to try, or is going to add what you mention to his list. He loves macOS and tolerates Windows but loves the platform Microsoft provides. At work, he currently enjoys all things web, being involved in software architecture, containers, kubernetes, and all things automation. He is also a remote worker, an assistant high school boys basketball coach, and non-profit board member.
Ed Spencer is a web focused contract software developer based in the Midlands in the UK. He has over 15 years of delivering high performance, business critical applications for a long list of well known brands.
Originally starting out as a database developer and on the Microsoft stack, he has transitioned into a full stack developer well versed in numerous technologies, ranging from .NET Core and Node.js on the server, to React and Angular on the client. Ed is also adept at performance tuning web applications.
He has been blogging for 10 years at https://edspencer.me.uk, which is his way of giving something back to the web development community.
Outside of development, Ed enjoys reading, exploring new places, and catching up with friends.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
ASP.NET Core 3 and React
Dedication
About Packt
Why subscribe?
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Code in Action
Conventions used
Get in touch
Reviews
Section 1: Getting Started
Understanding the ASP.NET Core React Template
Technical requirements
SPA architecture
Understanding the backend
Creating an ASP.NET Core and React templated app
Understanding the backend entry point
Understanding the Startup class
The ConfigureServices method
The Configure method
Custom middleware
Understanding controllers
Understanding the frontend
Understanding the frontend entry point
Running in development mode
Publishing process
Understanding the frontend dependencies
Understanding how the single page is served
Understanding how components fit together
Understanding how components access the backend web API
Summary
Questions
Further reading
Creating Decoupled React and ASP.NET Core Apps
Technical requirements
Creating an ASP.NET Core Web API project
Creating a React and TypeScript app
Understanding the benefits of TypeScript
Creating the app with CRA
Adding linting to React and TypeScript
Configuring Visual Studio Code to lint TypeScript code
Configuring linting rules
Adding automatic code formatting to React and TypeScript
Adding Prettier
Summary
Questions
Further reading
Section 2: Building a Frontend with React and TypeScript
Getting Started with React and TypeScript
Technical requirements
Understanding JSX
Creating function-based components
Creating a Header component
Creating our first component
Adding elements to the Header component
Creating a HomePage component
Creating mock data
Styling components
Styling using CSS class references
Understanding the benefits of CSS in JS
Installing Emotion
Styling the document body
Styling components using Emotion
Styling the App component
Styling the Header component
Styling the HomePage component
Implementing component props
Creating HomePage child components
Creating the QuestionList component
Creating the Question component
Wiring up the components
Optional and default props
Children prop
Function props
Implementing component state
Changing getUnansweredQuestions so that it's asynchronous
Using useEffect to execute logic
Using useState to implement component state
Handling events
Handling a button click event
Handling an input change event
Rendering optimization
Summary
Questions
Further reading
Routing with React Router
Technical requirements
Installing React Router with types
Declaring routes
Creating some blank pages
Creating a component containing routes
Redirecting a route
Handling routes not found
Implementing links
Using the Link component
Navigating programmatically
Using route parameters
Adding the question page route
Implementing more of the question page
Creating an AnswerList component
Using query parameters
Lazy loading routes
Summary
Questions
Further reading
Working with Forms
Technical requirements
Understanding controlled components
Reducing boilerplate code with generic components
Creating a Form component
Creating a Field component
Sharing state with a React context
Understanding a React context
Creating a form context
Creating a form context provider
Consuming the form context
Implementing the ask form
Implementing the answer form
Implementing validation
Adding validation rules to the Form component
Tracking validation errors with state
Invoking validation rules 
Rendering validation errors
Implementing validation on the ask and answer forms
Submitting forms
Handling form submission
Implementing form submission in the search, ask, and answer forms
Implementing form submission in the search form
Implementing form submission in the ask form
Implementing form submission in the answer form
Trying out our forms
Summary
Questions
Further reading
Managing State with Redux
Technical requirements
Understanding the Redux pattern
Principles
Key concepts
Installing Redux and Redux Thunk
Creating the state
Creating actions
Creating action creators
Implementing an action creator for getting unanswered questions
Implementing an action creator for posting a question
Implementing an action creator for clearing the posted question
Creating a reducer
Creating the store
Connecting components to the store
Adding a store provider
Connecting the home page
Connecting the ask page
Summary
Questions
Further reading
Section 3: Building an ASP.NET Core Backend
Interacting with the Database with Dapper
Technical requirements
Implementing the database
Creating the database
Creating database tables
Creating stored procedures
Understanding what Dapper is and its benefits
Installing and configuring Dapper
Reading data using Dapper
Creating the repository class
Creating a repository method to get questions
Creating a repository method to get questions by a search
Creating a repository method to get unanswered questions 
Creating a repository method to get a single question
Creating a repository method to check whether a question exists
Creating a repository method to get an answer
Writing data using Dapper
Adding methods to write data to the repository interface
Creating a repository method to add a new question
Creating a repository method to change a question
Creating a repository method to delete a question
Creating a repository method to add an answer
Managing migrations using DbUp
Installing DbUp into our project
Configuring DbUp to do migrations on app startup
Embedding SQL Scripts in our project
Performing a database migration
Summary
Questions
Further reading
Creating REST API Endpoints
Technical requirements
Creating an API controller
Creating an API controller for questions
Injecting the data repository into the API controller
Creating controller action methods
Creating an action method for getting questions
Extending the GetQuestions action method for searching
Creating an action method for getting unanswered questions
Creating an action method for getting a single question
Creating an action method for posting a question
Creating an action method for updating a question
Creating an action method for deleting a question
Creating an action method for posting an answer
Adding model validation
Adding validation to posting a question
Adding validation to updating a question
Adding validation to posting an answer
Removing unnecessary request fields
Removing unnecessary request fields from posting a question
Removing unnecessary request fields from posting an answer
Summary
Questions
Further reading
Creating a Real-Time API with SignalR
Technical requirements
Understanding the benefits of SignalR
Creating a SignalR hub
Pushing data to SignalR clients from an API controller
Creating the SignalR real-time API endpoint
Interacting with the SignalR real-time API from React
Installing the SignalR client
Setting up the client connection
Stopping the client connection
Adding CORS to our backend
Mapping a question from the real-time API to React state
Summary
Questions
Further reading
Improving Performance and Scalability
Technical requirements
Reducing database round trips
N+1 problem
Using WebSurge to load test our endpoint
Using Dapper multi-mapping to resolve the N+1 problem
Using Dapper multi results
Paging data
Adding test questions for the load test
Load testing the current implementation
Implementing data paging 
Making API controllers asynchronous
Testing the current implementation
Implementing an asynchronous controller action method
Mixing asynchronous and synchronous code
Caching data
Load testing the current implementation
Implementing a data cache
Using the data cache in an API controller action method
Reducing garbage collection
Load testing the current implementation
Implementing custom model binding 
Summary
Questions
Further reading
Securing the Backend
Technical requirements
Understanding OIDC
Setting up Auth0 with our ASP.NET Core backend
Setting up Auth0
Configuring our ASP.NET Core backend to authenticate with Auth0
Protecting endpoints
Protecting endpoints with simple authorization
Protecting endpoints with a custom authorization policy
Using the authenticated user when posting questions and answers
Summary
Questions
Further reading
Interacting with RESTful APIs
Technical requirements
Using fetch to interact with unauthenticated REST API endpoints
Getting unanswered questions from the REST API
Extracting out a generic HTTP function
Getting a question from the REST API
Searching questions with the REST API
Interacting with Auth0 from the frontend
Installing the Auth0 JavaScript client
Recapping the sign-in and sign-out flow
Creating the sign-in and sign-out routes
Implementing a central authentication context
Implementing the sign-in process
Implementing the sign-out process
Configuring Auth0 settings in our frontend
Testing the sign-in and sign-out processes
Controlling authenticated options
Displaying the relevant options in the header
Only allowing authenticated users to ask a question
Only allowing authenticated users to answer a question
Using fetch to interact with authenticated REST API endpoints
Posting a question to the REST API
Posting an answer to the REST API
Testing protected endpoints with Postman
Stopping a data state being set if the user navigates away from the page
Summary
Questions
Further reading
Section 4: Moving into Production
Adding Automated Tests
Technical requirements
Understanding the different types of automated test
Unit tests
End-to-end tests
Integration tests
Implementing .NET tests with xUnit
Getting started with xUnit
Testing controller action methods
Testing the action method to implement GetQuestions
Testing the action method to get a single question
Implementing React tests with Jest
Getting started with Jest
Testing React components
Testing the Page component
Testing the Question component
Testing the HomePage component
Implementing end-to-end tests with Cypress
Getting started with Cypress 
Testing asking a question 
Summary
Questions
Further reading
Configuring and Deploying to Azure
Technical requirements
Getting started with Azure
Signing up to Azure
Understanding the Azure services we are going to use
Configuring the ASP.NET Core backend for staging and production
Publishing our ASP.NET Core backend to Azure
Publishing to production
Publishing to staging
Configuring the React frontend for staging and production
Publishing the React frontend to Azure
Publishing to production
Publishing to staging
Summary
Questions
Further reading
Implementing CI and CD with Azure DevOps
Technical requirements
Getting started with CI and CD
Understanding CI and CD
Enabling our tests to run in CI and CD
Creating an Azure DevOps project
Implementing CI
Implementing CD
Deploying to staging
Deploying to production
Summary
Questions
Further reading
Assessments
Answers
Chapter 1 – Understanding the ASP.NET Core React Template
Chapter 2 – Creating Decoupled React and ASP.NET Core Apps
Chapter 3 – Getting Started with React and TypeScript
Chapter 4 – Routing with React Router
Chapter 5 – Working with Forms
Chapter 6 – Managing State with Redux
Chapter 7 – Interacting with the Database with Dapper
Chapter 8 – Creating REST API Endpoints
Chapter 9 – Creating a Real-Time API with SignalR
Chapter 10 – Improving Performance and Scalability
Chapter 11 – Securing the Backend
Chapter 12 – Interacting with RESTful APIs
Chapter 13 – Adding Automated Tests
Chapter 14 – Configuring and Deploying to Azure
Chapter 15 – Implementing CI and CD with Azure DevOps
Other Books You May Enjoy
Leave a review - let other readers know what you think
ASP.NET Core is an open source and cross-platform web application framework built by Microsoft. It follows on from the hugely popular ASP.NET version 4, with significant architectural changes making it much leaner and much more modular. ASP.NET Core is a great choice for building highly performant backends that interact with databases such as SQL Server that are hosted in the cloud, such as in Microsoft's cloud platform, Azure.
React was built by Facebook in order to improve the scalability of their code base, and was eventually open sourced in 2013. React is now a massively popular library for building component-based frontends and works fantastically well with many backend technologies, including ASP.NET Core.
This book will teach you how you can use both these technologies to create secure and performant single-page applications (SPAs) on top of SQL Server databases hosted in Microsoft Azure.
This book is primarily aimed at developers with an understanding of C# and a basic knowledge of JavaScript and who are interested in building SPAs with ASP.NET Core and React.
Chapter 1, Understanding the ASP.NET Core React Template, covers the standard SPA template that ASP.NET Core offers for React apps. It covers the programmatic entry points for both the frontend and backend and how they work together in the Visual Studio solution.
Chapter 2, Creating Decoupled React and ASP.NET Core Apps, explains how a more up-to-date ASP.NET Core and React solution can be created. This chapter includes the use of TypeScript, which is hugely beneficial when creating large-scale frontends.
Chapter 3, Getting Started with React and TypeScript, covers the fundamentals of React, such as JSX, props, state, and events. The chapter also covers how to create strongly typed components with TypeScript.
Chapter 4, Routing with React Router, introduces a library that enables apps with multiple pages to be efficiently created. It covers how to declare all the routes in an app and how these map to React components, including routes with parameters.
Chapter 5, Working with Forms, covers how to build forms efficiently in React. Generic form and field components are built step by step, which includes validation and submission. These components are then used to rapidly build forms in an app.
Chapter 6, Managing State with Redux, steps through how this popular library can help manage state across an app. A strongly typed Redux store is built along with actions and reducers with the help of TypeScript.
Chapter 7, Interacting with the Database with Dapper, introduces a library that enables us to interact with SQL Server databases in a performant manner. Both reading and writing to a database are covered, including mapping SQL parameters and results with C# classes.
Chapter 8, Creating REST API Endpoints, covers how to create a REST API that interacts with a data repository. Along the way, dependency injection, model binding, and model validation are also covered.
Chapter 9, Creating a Real-Time API with SignalR, starts by covering how these APIs differ from REST APIs. The chapter then covers how a React frontend can connect to a SignalR API and automatically receive updates on areas of the database without making an HTTP request.
Chapter 10, Improving Performance and Scalability, covers several ways of improving the performance and scalability of the backend, including reducing database round trips, making APIs asynchronous, and data caching. Along the way, several tools are used to measure the impact of the improvements.
Chapter 11, Securing the Backend, leverages ASP.NET identity along with JSON web tokens in order to add authentication to an ASP.NET Core backend. This chapter also covers the protection of REST API endpoints through the use of standard and custom authorization policies.
Chapter 12, Interacting with RESTful APIs, covers how a React frontend can talk to an ASP.NET Core backend using the JavaScript fetch function. This chapter also covers how a React frontend can gain access to protected REST API endpoints with a JSON web token.
Chapter 13, Adding Automated Tests, covers how to create a unit test and integration tests on the ASP.NET Core backend using xUnit. This chapter also covers how to create tests on pure JavaScript functions, as well as React components, using Jest.
Chapter 14, Configuring and Deploying to Azure, introduces Azure and then steps through deploying both the backend and frontend to separate Azure app services. This chapter also covers the deployment of a SQL Server database to SQL Azure.
Chapter 15, Implementing CI and CD with Azure DevOps, introduces Azure DevOps, before stepping through the creation of a build pipeline that automatically triggers when code is pushed to a source code repository. This chapter then examines setting up a release pipeline that deploys the artifacts from the build into Azure.
You need to know the fundamentals of C#, including the following:
How to create variables and reference them, including arrays and objects
How to create classes and use them
How to create conditional statements with the
if
and
else
keywords
You need to know the basics of JavaScript, including the following:
How to create variables and reference them, including arrays and objects
How to create functions and call them
How to create conditional statements with the
if
and
else
keywords
You need to know the basics of HTML, including the following:
Basic HTML tags, such as
div
,
ul
,
p
,
a
,
h1
, and
h2
, and how to compose them together to create a web page
How to reference a CSS class to style an HTML element
You need to have an understanding of basic CSS, including the following:
How to size elements and include margins and padding
How to position elements
How to color elements
An understanding of basic SQL is helpful, but not essential.
You will need the following technologies installed on your computer:
Google Chrome
: This can be installed at
https://www.google.com/chrome/
.
Visual Studio 2019
: This can be download and installed from
https://visualstudio.microsoft.com/vs/
.
.NET Core 3
: This can be downloaded and installed from
https://dotnet.microsoft.com/download/dotnet-core
.
Visual Studio Code
: This can be downloaded and installed from
https://code.visualstudio.com/
.
Node.js and npm
: This can be download and installed from
https://nodejs.org/
. If you already have these installed, make sure that Node.js is at least version 8.2 and that npm is at least version 5.2.
SQL Server 2017 Express Edition
: This can be downloaded and installed from
https://www.microsoft.com/en-gb/sql-server/sql-server-editions-express
.
SQL Server Management Studio
: This can be downloaded and installed from
https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms?view=sql-server-2017
.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packt.com
.
Select the
Support
tab.
Click on
Code Downloads
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/ASP.NET-Core-3-and-React-17. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781789950229_ColorImages.pdf.
Visit the following link to check out videos of the code being run:
http://bit.ly/2sZjjlp
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in, and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packt.com.
This section provides a high-level introduction to ASP.NET Core and React and how to create projects that enable them to work well together. We will create the project for the app that we'll build throughout this book, which will allow users to submit questions and other users to submit answers to them—a Q&A app.
This section comprises the following chapters:
Chapter 1
,
Understanding the ASP.NET Core React Template
C
hapter
2
,
Creating Decoupled React and ASP.NET Core Apps
React was Facebook's answer to helping more people work on the Facebook code base and deliver features quicker. React worked so well for Facebook that they eventually open sourced it (https://github.com/facebook/react). Today, React is a mature library for building component-based frontends (client-side code that runs in the browser); it is extremely popular and has a massive community and ecosystem. At the time of writing, React is downloaded over 5.8 million times per day, which has more than doubled in the last year.
ASP.NET Core was first released in 2016 and is now a mature open source and cross-platform web application framework. It's an excellent choice for building backends (application code that runs on the server) that interact with databases such as SQL Server. It also works well in cloud platforms such as Microsoft Azure.
In this first chapter, we'll start by learning about the single-page application (SPA) architecture. Then, we'll create an ASP.NET Core and React app using the standard template in Visual Studio. We will use this to review and understand the critical parts of a React and ASP.NET Core app. We'll learn where the entry points of both the ASP.NET Core and React apps are and how they integrate with each other. We'll also learn how Visual Studio runs both the frontend and backend together in development mode, as well as how it packages them up, ready for production. By the end of this chapter, we'll have gained fundamental knowledgeso that we can start building an app that uses both of these awesome technologies, and that we'll gradually build throughout this book.
In this chapter, we'll cover the following topics:
SPA architecture
Understanding the backend
Understanding the frontend
We'll use the following tools in this chapter:
Visual Studio 2019
: This can be downloaded and installed from
https://visualstudio.microsoft.com/vs/
. Make sure that the following features are selected in the installer:
ASP.NET and web development
Azure development
Node.js development
.NET Core 3.0
: This can be downloaded and installed from
https://dotnet.microsoft.com/download/dotnet-core
.
Node.js and npm
: These can be downloaded from
https://nodejs.org/
.
All the code snippets in this chapter can be found online at https://github.com/PacktPublishing/ASP.NET-Core-3-and-React-17. In order to restore code from this chapter, the source code repository should be downloaded and the project in the Chapter01 folder should be opened in Visual Studio.
Check out the following video to see the code in action:
http://bit.ly/2ZpsqaZ
An SPA is a web app that loads a single HTML page that is dynamically updated by JavaScript as the user interacts with the app. Imagine a simple sign-up form where a user can enter a name and an email address. Once the user fills out and submits the form, a whole page refresh doesn't occur. Instead, some JavaScript in the browser handles the form submission with an HTTP POST request and then updates the page with the result of the request. Refer to the following diagram:
So, after the first HTTP request that returns the single HTML page, subsequent HTTP requests are only for data and not HTML markup. All the pages are rendered in the client's browser by JavaScript.
So, how are different pages with different URL paths handled? For example, if I enter https://qanda/questions/32139 in the browser's address bar, how does it go to the correct page in the app? Well, the browser's history API lets us change the browser's URL and handle changes in JavaScript. This process is often referred to as routing and, in Chapter 4, Routing with React Router, we'll learn how we can build apps with different pages.
The SPA architecture is what we are going to use throughout this book. We'll use React to render our frontend and ASP.NET Core for the backend API.
Now that we have a basic understanding of the SPA architecture, we'll take a closer look at a SPA-templated app that Visual Studio can create for us.
In this section, we are going to start by creating an ASP.NET Core and React app using the standard template in Visual Studio. This template is perfect for us to review and understand basic backend components in an ASP.NET Core SPA.
Let's open Visual Studio and carry out the following steps to create our templated app:
In the start-up dialog, choose
Create a new project
:
Next, choose
ASP.NET Core Web Application
in the wizard that opens and click the
Next
button:
Give the project a name of your choice and choose an appropriate location to save the project to. Click the
Create
button to create the project:
Another dialog will appear that allows us to specify the version of ASP.NET Core we want to use, as well as the specific type of project we want to create. Select
ASP.NET Core 3.0
as the version and
React.js
in the dialog, and then click the
Create
button, which will create the project:
Now that the project has been created, let's press
F5
to run the app. After a minute or so, the app will appear in a browser:
We'll find out later in the chapter why the app took so long to run the first time. Great—we've created the ASP.NET Core React SPA. Now, let's inspect the backend code.
An ASP.NET Core app is a console app that creates a web server. The entry point for the app is a method called Main in a class called Program, which can be found in the Program.cs file in the root of the project:
public class Program{ public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>();}
This method creates a web host using WebHost.CreateDefaultBuilder, which configures items such as the following:
The location of the root of the web content
Where the settings are for items such as the database connection string
The logging level and where the logs are output
We can override the default builder using fluent APIs, which start with Use. For example, to adjust the root of the web content, we can add the highlighted line in the following snippet:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args)
.UseContentRoot("some-path")
.UseStartup<Startup>();
The last thing that is specified in the builder is the Startup class, which we'll look at in the following section.
The Startup class is found in Startup.cs and configures the services that the app uses, as well as the request/response pipeline.
Web API resources are implemented using controllers. Let's have a look at the controller the template project created by opening WeatherForecastController.cs. This contains a class called WeatherForecastController that inherits from ControllerBase with a Route annotation:
[ApiController][Route("[controller]")]
public class WeatherForecastController :
ControllerBase
{ ...}
The annotation specifies the web API resource URL that the controller handles. The [controller] object is a placeholder for the controller name, minus the word Controller. This controller will handle requests to weatherforecast.
The method called Get in the class is called an actionmethod. Action methods handle specific requests to the resource for a specific HTTP method and subpath. We decorate the method with an attribute to specify the HTTP method and subpath the method handles. In our example, we are handling an HTTP GET request to the root path (weatherforecast) on the resource:
[HttpGet]public IEnumerable<WeatherForecast> Get(){ ...}
Let's have a closer look at the web API at runtime by carrying out the following steps:
Run the app in Visual Studio by pressing
F5.
When the app has opened in our browser, press
F12
to open the browser developer tools and select the
Network
panel.
Select the
Fetch data
option on the top navigation bar. An HTTP
GET
request to
weatherforecast
will be shown:
An HTTP response with a
200
status code is returned with JSON content:
If we look back at the Get action method, we are returning an object of the IEnumerable<WeatherForecast> type. The MVC middleware automatically converts this object into JSON and puts it in the response body with a 200 status code for us.
So, that was a quick look at the backend that the template scaffolded for us. In the next section, we'll walk through the React frontend.
It's time to turn our attention to the React frontend. In this section, we'll discover where the single HTML page is that hosts the React app. We'll also understand why it took over a minute to run the app for the first time.
The publishing process is the process of building artifacts to run an application in a production environment.
Let's carry on and inspect the XML ASP.NET Core project file and look at the Target element, which has the following Name attribute: PublishRunWebPack. The following code executes a set of tasks when the Visual Studio project is published:
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish"> <!-- As part of publishing, ensure the JS resources are freshly built in production mode --> <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" /> <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" /> <!-- Include the newly-built files in the publish output --> <ItemGroup> <DistFiles Include="$(SpaRoot)build\**" /> <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)"> <RelativePath>%(DistFiles.Identity)</RelativePath> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </ResolvedFileToPublish> </ItemGroup></Target>
The first task that is run is the execution of the npm install command via an Exec task. This will ensure that all the dependencies are downloaded and installed. Obviously, if we've already run our project in debug mode, then the dependencies should already be in place.
The next task is an Exec task that runs the following npm command:
>
npm run build
This task will run an npm script called build. If we look in the package.json file again, we'll see this script in the scripts section:
"scripts": { "start": "rimraf ./build && react-scripts start",
"build": "react-scripts build"
, "test": "cross-env CI=true react-scripts test --env=jsdom", "eject": "react-scripts eject", "lint": "eslint ./src/"}
This references the create-react-app scripts, which bundle the React app ready for production, optimizing it for great performance,and outputting the content into a folder called build.
The next set of tasks defined in the ItemGroup element take their content from the build folder and place it in the publish location, along with the rest of the content to publish.
Let's give this a try and publish our app:
In
Solution Explorer
, right-click on the project and select the
Publish...
option.
Choose
Folder
as the target and enter a folder to output the content to.
Click the
Publish
drop-down menu and then choose the
Publish immediately
option
to start the publishing process:
After a while, we'll see the content appear in the folder we specified, including a ClientApp folder. If we look in this ClientApp folder, we'll see a build folder containing the React app, ready to be run in a production environment. Notice that the build folder contains index.html, which is the single page that will host the React app in production.
Earlier, we learned that frontend dependencies are defined in package.json. Why not just list all the dependencies as script tags in index.html? Why do we need the extra complexity of npm package management in our project? The answer is that a long list of dependencies is hard to manage. If we used script tags, we'd need to make sure these are ordered correctly. We'd also be responsible for downloading the packages, placing them locally in our project, and keeping them up to date. We have a huge list of dependencies in our scaffolded project already, without starting work on any functionality in our app. For these reasons, managing dependencies with npm has become an industry standard.
Let's open package.json again and look at the dependencies section:
"dependencies": { "bootstrap": "^4.1.3", "jquery": "3.4.1", "merge": "^1.2.1", "oidc-client": "^1.9.0", "react": "^16.0.0", "react-dom": "^16.0.0", "react-router-bootstrap": "^0.24.4", "react-router-dom": "^4.2.2", "react-scripts": "^3.0.1", "reactstrap": "^6.3.0", "rimraf": "^2.6.2"},
We've already observed the react dependency, but what is the react-dom dependency? Well, React doesn't just target the web; it also targets native mobile apps. This means that react is the core React library that is used for both web and mobile, and react-dom is the library that's specified for targeting the web.
The react-router-dom package is the npm package for React Router and helps us to manage the different pages in our app in the React frontend without a round-trip to the server. We'll learn more about React Router in Chapter 4, Routing with React Router. The react-router-bootstrap package allows Bootstrap to work nicely with React Router.
We can see that this React app has a dependency for Bootstrap 4.1 with the bootstrapnpm package. So, Bootstrap CSS classes and components can be referenced to build the frontend in our project. The reactstrap package is an additional package that allows us to consume Bootstrap nicely in React apps. Bootstrap 4.1 has a dependency on jQuery, which is the reason for the jquery package dependency.
The merge package contains a function that merges objects together and oidc-client is a package for interacting with OpenID Connect (OIDC) and OAuth2. We'll make use of the oidc-client package in Chapter 11, Securing the Backend.
The final dependency that we haven't covered yet is rimraf. This simply allows files to be deleted, regardless of the host operating system. We can see that this is referenced in the start script:
"scripts": { "start": "
rimraf ./build
&& react-scripts start", ...}
Earlier in this chapter, we learned that this script is invoked when our app is running in development mode. So, rimraf ./build deletes the build folder and its contents before the development server starts.
If we look further down, we'll see a section called devDependencies. These are dependencies that are only used during development and not in production:
"devDependencies": { "ajv": "^6.9.1", "babel-eslint": "^10.0.1", "cross-env": "^5.2.0", "eslint": "^5.12.0", "eslint-config-react-app": "^4.0.1", "eslint-plugin-flowtype": "^2.0.0", "eslint-plugin-import": "^2.14.0", "eslint-plugin-jsx-a11y": "^6.2.1", "eslint-plugin-react": "^7.11.1"},
The following is a brief description of these dependencies:
ajv
allows us to validate JSON files.
cross-env
allows us to set environment variables, regardless of the host operating system. If you look at the
test
script in the
scripts
section of the
package.json
file, it uses
cross-env
to set a
CI
environment variable.
The remaining dependencies are all designed to enable linting with
ESLint
. The linting process checks for problematic patterns in code according to a set of rules. We'll learn more about ESLint in
Chapter 3
,
Getting Started with React and TypeScript
.
Let's move on and learn how the single page is served and how the React app is injected into it.
We know that the single page that hosts the React app is index.html, so let's examine this file. This file is found in the public folder in the ClientApp folder. The React app will be injected into the div tag that has an id of root:
<div id="root"></div>
Let's run our app again in Visual Studio to confirm that this is the case by pressing F5. If we open the developer tools in the browser page that opens and inspect the DOM in the Elements panel, we'll see this div with the React content inside it:
Notice the script tag at the bottom of the body tag. This contains all the JavaScript code for our React app, including the React library itself. However, this script tag doesn't exist in the source index.html file, so how did it get there in the served page? Webpack added it after bundling all the JavaScript together into bundle.js. If we look in the ClientApp folder and subfolders, the static folder doesn't exist. The bundle.js file doesn't exist either. What's going on? These are virtual files that are created by the Webpack development server. Remember that, when we run the app with Visual Studio debugger, the Webpack development server serves index.html. So, bundle.js is a virtual file that the Webpack development server creates.
Now, what happens in production mode when the Webpack development server isn't running? Let's have a closer look at the app we published earlier in this chapter. Let's look in the index.html file in the Build folder in the ClientApp folder. The script tag at the bottom of the body tag will look something like the following:
<script src="/static/js/main.
eebeebd5
.js"></script>
The highlighted part of the filename will vary each time the app is published. The filename is unique for each build in order to break browser caching. If we look for this JavaScript file in our project, we'll find that it does exist. So, in production mode, the web server will serve this physical JavaScript file.
If we open this JavaScript file, it contains all the JavaScript for our app. The JavaScript is minified so that the file can be downloaded to the browser nice and quick.
However, the file isn't small and contains a lot of JavaScript. What's going on here? Well, the file contains not only our JavaScript app code but also the code from all the dependencies, including React itself.