34,79 €
Today, full-stack development is the name of the game. Developers who can build complete solutions, including both backend and frontend products, are in great demand in the industry, hence being able to do so a desirable skill. However, embarking on the path to becoming a modern full-stack developer can be overwhelmingly difficult, so the key purpose of this book is to simplify and ease the process.
This comprehensive guide will take you through the journey of becoming a full-stack developer in the realm of the web and .NET. It begins by implementing data-oriented RESTful APIs, leveraging ASP.NET Core and Entity Framework. Afterward, it describes the web development field, including its history and future horizons. Then, you’ll build webbased Single-Page Applications (SPAs) by learning about numerous popular technologies, namely TypeScript, Angular, React, and Vue. After that, you’ll learn about additional related concerns involving deployment, hosting, and monitoring by leveraging the cloud; specifically, Azure.
By the end of this book, you’ll be able to build, deploy, and monitor cloud-based, data-oriented, RESTful APIs, as well as modern web apps, using the most popular frameworks and technologies.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 390
Veröffentlichungsjahr: 2018
Copyright © 2018 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(s), 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: Kunal ChaudhariAcquisition Editor: Noyonika DasContent Development Editor: Francis CarneiroTechnical Editor: Surabhi KulkarniCopy Editor: SafisProject Coordinator: Sheejal ShahProofreader: Safis EditingIndexer: Rekha NairGraphics: Alishon MendonsaProduction Coordinator: Arvindkumar Gupta
First published: October 2018
Production reference: 1301018
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78862-288-2
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,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
Mapt is fully searchable
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.
Tamir Dresher is the chief architect of Clarizen, a leading SaaS company in work collaboration and project management. Prior to that, he was a senior architect and leader of the cloud division at CodeValue, Israel. Tamir has helped organizations and start-ups create scalable distributed systems with .NET and is a prominent member of Israel's Microsoft developers' community. He was awarded Microsoft MVP for his contributions as a conference speaker, organizing developer-community events, and authoring Rx . NET in Action. As part of his role as Professor of Software Engineering at the Ruppin Academic Center, Tamir loves teaching and mentoring students and speaking at international conferences. His Twitter handle is @tamir_dresher.
Amir Zuker, a founder of CodeValue and its web division leader, is a senior software architect specializing in .NET and web-related technologies.Amir has headed up large development teams, conducted lectures and workshops, and has tackled various technological obstacles head-on in both frontend and backend products, including cloud, on-premise, and IoT solutions.A qualified instructor and consultant, he has helped dozens of companies build their systems from the ground up, including areas of recruitment, business analysis, architecture, design, implementation, testing, and DevOps.You can reach out to him via Twitter, @AmirZuker.
Shay Friedman is the CTO and VP, R&D, of Jifiti. With 20 years' experience in the software development world, Shay spearheads and manages the many technologies that Jifiti utilizes on a daily basis. Prior to that, Shay co-founded Pickspace, a VC-backed start-up in the field of real-estate tech. As CTO, he led the company's development efforts and helped it become a world leader in co-working space-related technologies. Prior to Pickspace, Shay co-founded CodeValue, one of the leading tech consulting companies in Israel, where he managed the web division, consulted dozens of companies, conducted training courses, and more. Shay is a renowned international speaker, loves playing basketball, and is endeavoring to improve his guitar playing.
Shama Hoque has more than 8 years' experience as a software developer and mentor, with a master's in software engineering from Carnegie Mellon University.
She specializes in full stack development with JavaScript, and currently makes web-based prototypes for R&D start-ups in California, while training aspiring software engineers and teaching web development to CS undergrads in Bangladesh.
She is also the author of Packt's Full Stack React Projects book, released in May 2018.
Antonio Esposito is a Microsoft Certified Trainer, software architect, father, son, and lover of cooking and eating. He has been addicted to computer programming from age eight, a developer since 2002, and a speaker from 2010. He has moved across Europe in the last fifteen years working as freelance consultant or speaker for companies such as UniCredit Bank, Ferrari F1 Racing Team, Microsoft Italy, IBM, and many others. He actively attends as a speaker at a lot of conferences, such as MCT Summit and WPC Italy. He is already an author for Packt with Learning .NET High Performance Programming in 2014 and Reactive Programming for .NET Developers in 2015.
Paul Johnson has been writing software since the early 1980s on machines ranging from the ZX81 and servers to his trusty Mac, and has used more languages than he can remember. He is a qualified scuba diver and college lecturer. Paul lives with his wife, kids, and pets, and listens to an inordinate amount of rock and metal on Primordial Radio. This is his third book for Packt.
He is an avid biker and volunteers for the Merseyside and Cheshire Blood Bikes on a regular basis and is also currently working on a proposal for his 4th book with Packt.
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
Hands-On Full-Stack Web Development with ASP.NET Core
PacktPub.com
Why subscribe?
Packt.com
Contributors
About the authors
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
Conventions used
Get in touch
Reviews
Becoming a Full-Stack .NET Developer
The full-stack developer
Full-stack development
Backend fundamentals
Hypertext Transfer Protocol 
HTTP is a stateless protocol
HTTP/2
Representational State Transfer
ASP.NET Core
Frontend fundamentals
 Hypertext Markup Language 
CSS
JavaScript
TypeScript
JavaScript frontend frameworks
Angular
React
Vue.js
Summary
Setting Up Your Development Environment
Visual Studio
Installing Visual Studio Community
Node.js and npm
Installing Node.js
TypeScript
Installing TypeScript
Google Chrome
Fiddler
Installing Fiddler
Summary
Creating a Web Application with ASP.NET Core
ASP.NET Core overview
.NET Core
Open source
Lightweight and fast
Modular
Host anywhere
Creating an ASP.NET Core application
Default files in an ASP.NET Core project
Predefined project templates
The Startup class
Code execution order
Different startups for different environments
Changing the Startup class name
Serving static files
The content root and web root folders
Setting the server to serve static files
Serving default documents
Configuring the available MIME types
Getting familiar with the ASP.NET Core MVC framework
The MVC pattern
MVC in SPAs
Adding MVC to ASP.NET Core
Controllers
Views
View files and their location
Creating a view
Routing
Adding routes
Adding routes via UseMvc
Adding routes via route attributes
Routing in SPAs
Summary
Building REST APIs with ASP.NET Core Web API
Overview — REST APIs with ASP.NET Core API
Creating a simple API 
Inspecting your APIs using Fiddler and Postman
Fiddler
Postman
Routing
Conventional routing
Defining a new route template
Attribute-based routing
Parameterizing the route template
Default values
Constraints
The model
Model binding
Query strings
Message body
Header values
Model validation
Generating a response of different types
Explicit return type
IActionResult and ActionResult<T>
Asynchronous actions
Controller response helper methods
Summary
Persisting Data with Entity Framework
Installing Entity Framework Core 
Creating your data model
Defining the entities
The DbContext
Configuring the model mapping
Configuring the database connection with DbContextOptions<TContext>
Creating a database with EF Core migrations
Creating a new migration
Adding automatic migrations
Connecting to the database 
Adding seed data
Saving data
Updating and deleting objects
Querying data
Loading related entities
Creating conditional queries with the IQueryable deferred execution
Mapping the API results to DTOs
Mapping entities to DTOs with AutoMapper
Summary
Securing the Backend Server
Authenticating and authorizing application users
Adding identity management entities to your data model
Enabling the identity infrastructure 
Enabling token-based authentication with JSON Web Token
The authentication and authorization flow
Creating a user registration API
Implementing the login functionality and generating a JWT
Adding user claims
Configuring your backend to always require authentication  
Configuring an action to allow anonymous access
Controlling access to APIs with authorization
Adding claims that can be used for authorization
Authorizing users by their role
Creating an authorization policy
Enabling Cross-Origin Resource Sharing
Summary
Troubleshooting and Debugging
Adding logging to your application
Writing a log message from the controller
Filtering log messages
Log providers
Provider-specific configuration and filters
Enabling diagnostics with Application Insights
Responding gracefully in the event of errors and exceptions
Adding a correlation identifier to responses
The developer exception page
Adding a global exception handler
Making your APIs discoverable and self-documenting with the OpenAPI standard (Swagger)
Generating a Swagger file from the ASP.NET Core application
Adding the Swagger UI to your application
Sending a request through the Swagger UI 
Generating client code from a Swagger file
Swagger editor
Summary
Getting Started with Frontend Web Development
Getting started with frontend web development
HTML
CSS
JavaScript
Notable progress and future development
Web components
WebAssembly
The Everyday Market app
Homepage with product listings
Product page
New product page
jQuery
Everyday Market homepage using jQuery
Initial layout
REST API access
Menu item template
Category menu items query
Product item template
Product cards query
Busy indicator
Summary
Getting Started with TypeScript
TypeScript
The TypeScript compiler
Types
Basic types
Arrays
Enums
Objects
Functions
Type inference
Type casting
Type aliasing
Interfaces
Extending interfaces
Classes
Access modifiers
Members
Class inheritance and interface implementation
Modules
Decorators
Summary
Further reading
App Development with Angular
Angular overview
Building blocks
Angular CLI
Setup and common commands
Linting code
Running tests
Running the project
Key app parts
Modules
Components
Header component
Global styles
Assets
Category-menu-item component
category-menu component
products-page component
Data binding
Interpolation binding
Property binding
Event binding
Two-way binding
Component interaction
Input
ngFor
Output
Injectable services
HTTP
Busy indicator
ngIf
Distribution
Environments
Summary
Implementing Routing and Forms
Client-side routing
Using Angular Router
Implementing a routed page
Implementing template-driven forms in Angular
Using Angular's ngModel directive
Implementing form validation
Element references
Summary
App Development with React
React overview
Building blocks
Creating a React app
Key app parts
Components
Render function
JSX
Using JSX
Header component
Props
State
setState
Stateless functional components
CategoryMenu
List rendering
Product listing
Busy indicator
Conditional rendering
Summary
App Development with Vue
Vue.js overview
Building blocks
Vue CLI
Key app parts
Components
Single file components
Header component
Global styles
Assets
Data binding and component interaction
Component definition object
Props
Interpolation binding
Property binding
Data
Methods
Events
Computed
The category menu
List rendering
Product listing
Busy indicator
Conditional rendering
Summary
Moving Your Solution to the Cloud
What is cloud computing?
Virtualization and automation
Cloud service models
Working with Microsoft Azure 
Creating a Microsoft Azure account
Getting familiar with the portal and with the command line
The Azure portal
Azure portal blades
Using the Azure CLI
The Azure account and resources model
Azure Resource Manager
Resource groups
ARM templates
Pricing and billing
Summary
Deploying to Microsoft Azure
Creating a production environment with Azure App Service
App Service plan
Creating your App Service 
Linking a SQL server database to the application 
Choosing an Azure SQL pricing tier
Deploying the GiveNTake backend service from Visual Studio
Creating an automated build and release pipeline in Azure DevOps 
Creating a build pipeline
Creating a release pipeline that will deploy to Azure
Configure the release pipeline artifact
Configure the release pipeline stage
Deploying the GiveNTake frontend to Azure App Service
Configuring Azure App Service to work with an Angular application
Creating a build pipeline for the Angular app
Creating a release pipeline for the Angular app
Summary
Taking Advantage of Cloud Services
Scaling your service
Scaling up your App Service 
Scaling out your App Service 
Autoscaling
Cloud Diagnostics with Application Insights
Connecting Azure Application Insights to your App Service
Connecting the ASP.NET Core logger to Azure Application Insights
Setting the Instrumentation Key in Application settings
Analyzing Application Insights telemetry
End-to-end transaction analysis 
Advanced querying and visualizing with Analytics
Application map
Testing in production with Deployment slots
Deploying to a Deployment slot
Swapping between Deployment slots
Testing in production
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is intended for junior developers who are seeking to improve their web development skills and become full-stack developers.
It teaches the new way of writing web applications via the concepts of single-page applications and REST APIs. After reading and practicing with the book, you will be able to build both the backend and frontend parts of web applications, thereby becoming a full-stack developer.
This book is intended for C# programmers interested in developing, and further enhancing, their skills in the development of web applications running in the cloud. Additionally, novice web developers who wish to learn the modern way of writing web apps using several leading frameworks will benefit a great deal from this book. This book is for junior developers with prior experience in writing C# applications, and will teach you the basics of creating backend applications with ASP.NET Core, and frontend applications with modern technologies.
Chapter 1, Becoming a Full-Stack .NET Developer, explains the meaning of full-stack development and what technologies will be covered throughout the rest of the book.
Chapter 2, Setting Up Your Development Environment, guides you through the installation of tools that you will use throughout this book.
Chapter 3, Creating a Web Application with ASP.NET Core, teaches the basics of ASP.NET Core as a framework for creating web applications.
Chapter 4, Building REST APIs with ASP.NET Core Web API, explains why REST architectural styles are preferable when it comes to creating backends and teaches you how to create a REST API with ASP.NET Core.
Chapter 5, Persisting Data with Entity Framework, defines the data model you will use for the GiveNTake sample application this book creates, and teaches you how to store and query data from a relational database using EF Core.
Chapter 6, Securing the Backend Server, teaches you how to make your service more secure and how to add authentication and authorization so that you can control who will use your APIs.
Chapter 7, Troubleshooting and Debugging, covers a number of techniques that will be valuable when you develop your backend application and that will allow you to troubleshoot potential issues.
Chapter 8, Getting Started with Frontend Web Development, covers the history, as well as current and future developments, in the web development field, focusing on HTML, CSS, and JavaScript. At the same time, it illustrates the app that you will build throughout the book and demonstrates a classic implementation of that using jQuery.
Chapter 9, Getting Started with TypeScript, covers TypeScript, which is designed and maintained by Microsoft. In this chapter, we will cover the fundamentals of TypeScript, such as types, interfaces, classes, modules, decorators. TypeScript uses static typing and assists tremendously with maintainability and productivity.
Chapter 10, App Development with Angular, explains what Angular is, along with its features, and then teaches you how to build web apps using Angular as it takes you through a detailed step-by-step tutorial in building an actual app.
Chapter 11, Implementing Routing and Forms, teaches you additional features in Angular, specifically, its rich support for routing and forms as you add these to the app you built in the previous chapter.
Chapter 12, App Development with React, explains what React is, along with its features, and then teaches you how to build web apps using React as it takes you through a detailed step-by-step tutorial in building an actual app.
Chapter 13, App Development with Vue, explains what Vue is, along with its features, and then teaches you how to build web apps using Vue as it takes you through a detailed step-by-step tutorial in building an actual app.
Chapter 14, Moving Your Solution to the Cloud, reviews the meaning of the cloud and guides you in the first steps of creating your account in Microsoft Azure.
Chapter 15, Deploying to Microsoft Azure, explains the steps you need to carry out in order to deploy and host your application in Microsoft Azure and teaches you how to automate the process.
Chapter 16, Taking Advantage of Cloud Services, demonstrates a number of valuable services that the Azure cloud has to offer that will make it easier for you to scale your service based on demand, troubleshoot problems, and create multiple environments for the purpose of testing new features.
You should have experience of, and feel comfortable with, programming with C#.
Prior knowledge of ASP.NET or other .NET web technologies, along with HTML and JavaScript, is recommended.
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.packt.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 & Errata
.
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/Hands-On-Full-Stack-Web-Development-with-ASP.NET-Core. 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://www.packtpub.com/sites/default/files/downloads/9781788622882_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "For example, if you need to use System.IO, you can get it from NuGet as a separate library, without the need to add and load the entire System assembly."
A block of code is set as follows:
public static IWebHostBuilder CreateWebHostBuiler(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>();
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
WebHost.CreateDefaultBuilder(args)
.UseContentRoot(Path.Combine(Directory.GetCurrentDirectory(), "/client"))
.UseStartup<Startup>() .Build();
Any command-line input or output is written as follows:
dotnet new web
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Open Visual Studio and go to File | New | Project...."
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.packt.com/submit-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.
The World Wide Web (WWW) has changed tremendously since its beginning. In less than 30 years, it has morphed from a document-sharing space into a sophisticated platform that joins the world together. The role of developers, the ones behind the scenes of this global craze, has also changed accordingly.
Having started with the title Web Master — a job that required some knowledge of HTML and a little bit of Perl — the web developer role has changed into full-stack developer. A short title with a big meaning. As a full-stack developer, you're required to master many programming languages, markup languages, and tools — and that is before you even start working on the actual project at hand. It's an extremely challenging role, yet one of the most satisfying in the software industry.
In this chapter, we'll demystify what it means to be a full-stack developer and go through the basic concepts and ideas such a developer needs to know. We will cover the following topics:
The full-stack developer
Backend fundamentals
Frontend fundamentals
Full-stack developer is a term that describes a developer who is experienced with the entire stack of application development — the backend side, which also includes the database, and the frontend side, which is commonly known as the user interface. It sounds like only a few selected developers who have a vast amount of knowledge and incredible, almost mythical, skills are qualified to bear this title - full-stack. However, the truth is different—nobody can know everything, and the secret is to pick a specific stack of technologies and deep dive into them. Being a full-stack developer will allow you to develop any kind of application, and thus opens up an endless amount of opportunities.
Full-stack development refers to a client-server architecture model, or, as it's more commonly known, the frontend and backend. These are different in almost every single aspect. Backend development refers to writing code for the server side—handling data, providing APIs, managing security, deployment, and more. Frontend development refers to writing code for the client side—in our case, web clients running in users' browsers, working on the user interface, presentation logic, browser compatibility, performance, responsiveness, and more.
The backend and frontend parts do not usually share code; it might be written in entirely different programming languages, and run on different types of machines and in geographical locations. They communicate through the network via the HTTP protocol with the help of standards, ideas, practices, and architectural styles such as REST and JSON. The most notable difference between the backend and the frontend is the intended end user that interacts with each one of them—the backend interface serves computer systems, while the frontend interface serves human beings, as shown in the following diagram:
Being a full-stack developer means that you are an all-around developer who understands the different concepts and responsibilities of each part and, moreover, is able to take an idea and implement it from the very first line of code to a finished and deployed product.
In order to begin diving into full-stack development, let's get familiar with the concepts, responsibilities, and technologies for each part of the stack.
The backend side of a system is one or more applications running on machines that are commonly referred to as servers. The purpose of these applications is to serve requests coming from other applications—clients—and execute the necessary steps to accomplish the given request (validate the input, verify the requester's permissions, query and update rows in the database, run algorithms and workflows, and, at the end, return a response that the client side can then use to determine how to proceed.
The backend side of a project is like the soil in a flower field—if the soil is healthy, it enables a flourishing field with lovely flowers. However, if the soil is dry and not taken care of, the flowers will die and the field will cease to exist.
In our case, the field is the backend server and the flowers are our users—the backend needs to be reliable, secure, fast, and scalable in order to support many happy users and to create a successful product.
The world of backend development is extensive — there are a vast amount of programming languages and technologies that you can choose from. Each of them looks at this world from a slightly different angle, enabling different targets. For example, C# is a very powerful language that comes with plenty of handy tools, JavaScript allows you to write the backend and the frontend using the same programming language, and Python is suitable for systems based on math and complex algorithms.
Fortunately, whatever the technology of choice is, its interface to external systems will follow the same protocols as other backend systems — HTTP and JSON, which allow the creation of RESTful APIs. This enables strict separation of concerns between the backend and the frontend — each of them can be created using a different set of technologies but they will still be able to communicate flawlessly.
Hypertext Transfer Protocol (HTTP) is the foundation of communication on the WWW. It defines the format of messages and the way they are transmitted between the client and the server.
HTTP has two sides to communication — the client and the server. On web applications, the client is the user's web browser and the server is the backend server. Communication happens when the client creates a message called an HTTP request, sends it to the server, and the server, in turn, responds with an HTTP response, as shown in the following diagram:
Each HTTP request consists of a few pieces of information:
URI
: The web address or IP address that identifies the server. For example,
http://example.com or http://192.168.0.1
.
Method:
The action that should be taken upon the requested resource. For example,
GET
indicates data retrieval and
POST
indicates data creation.
Body
: Contains the data to be sent to the server, if any. The most popular data format for HTTP requests is JSON but, generally, data can be formatted in any format that the server understands.
Headers
: An optional set of metadata key-value pairs that add information to a request.
The server retrieves this request, executes related logical steps (commonly known as business logic), and forms an HTTP response to be sent back to the client. This response includes a few details:
Status code
: A three-digit integer that describes the result of the request. For example, 200 means OK, 500 means there was an error in the server, and 404 means the requested resource was not found.
Body
: The data sent back from the server, if any. As with the request body, JSON is the common data format, but any other format is valid as well.
Headers
: An optional set of metadata key-value pairs that add information about the response.
The HTTP protocol is a stateless one. This means that every HTTP request the server receives is independent and does not relate to requests that came prior to it. For example, imagine the following scenario: a request is made for the first ten user records, then another request is made for the next ten records.
On a stateful protocol, the server remembers each client position inside the result-set, and therefore the requests will be similar to:
Give me the first ten user records
Give me the next ten records
On a stateless protocol, the requests will be a bit different. The server doesn't hold the state of its client, and therefore the client's position in the result-set needs to be sent as part of the requests:
Give me user records on index 1 to 10
Give me user records on index 11 to 20
The slight difference between these examples represents the different approaches. On stateful protocols, you assume that the server knows everything about the previous requests, while on a stateless protocol you assume the opposite—the server doesn't know anything about the previous requests, which is why you send all the necessary information with each and every request.
On the one hand, this makes web service development more challenging, since creating fast, stateless service is not an easy task. On the other hand, this enables services to scale out quickly and support millions of users rather easily.
HTTP was created by Sir Tim Berners-Lee, the founder of the World Wide Web, back in 1989. The first version, HTTP 1.0, was introduced in 1996, followed by HTTP 1.1, which was introduced in 1997. HTTP 1.1 is still the most common version of HTTP out there.
In May 2015, HTTP/2 was released, which provided several improvements and enhancements to the old HTTP 1.1 protocol, such as server-to-client push messages and binary data support, to name just a couple. Ever since, it has been adopted by many websites and is slowly becoming the standard version of choice for websites.
Representational state transfer (REST) is an architectural style for resource-oriented services. It is used by most web applications today to standardize communication between the client and the server. If HTTP was the spoken language, REST would be a set of rules for that language.
REST-based web services, also known as RESTful APIs, have a few constraints they need to follow:
Consistent interface
: Every entity is a resource that will have a unique endpoint— a unique base URL. All operations on a resource will be available via that URL.
URL and HTTP methods
: When a resource URL is combined with an HTTP method, it describes an operation performed on the resource. For example,
GET
means retrieving data,
POST
means creating data, and
DELETE
means deleting data.
Statelessness
: Just like the HTTP protocol, RESTful services are stateless. This means that each request is independent and information regarding previous requests is never used.
Cacheable
: For each response, the server defines whether it is cacheable or not. Once a response is set as cacheable, the client caches it and uses the data from the cache instead of requesting it from the server again and again.
For example, in an application that manages students, we could have the following services:
URL
HTTP Method
Description
/students
GET
Retrieve all students
/students
POST
Create a new student
/students/123
GET
Retrieve student with ID 123
/students/123
PUT
Update student with ID 123
/students/123
DELETE
Delete student with ID 123
REST has become the de facto style of communication between the backend and the frontend. This is especially because it is a simple concept, yet very powerful — it makes the backend understandable to other developers and simple to modify and scale, and supports multiple types of clients, including web and mobile.
ASP.NET Core is a free, open-source web framework developed by Microsoft. It provides features that enable building the backend for modern web applications, as well as web APIs. The programming language that is used for the development of ASP.NET Core is C# or any other .NET-based programming language.
ASP.NET Core is a redesign of the popular ASP.NET Model View Controller (MVC) and ASP.NET Web API frameworks. The result is a leaner and more modular framework that can run on the full .NET Framework on Windows and .NET Core on other platforms.
Both parts of the framework, MVC and Web API, help in creating modern web applications. MVC is for building traditional web applications in which rendering is done on the server-side, but also supports integration with modern JS libraries and client-side rendering. ASP.NET offers many web development features out of the box, such as security, data validation, deployment, and more. ASP.NET Web API is for creating RESTful web services that serve modern frontend applications, mobile apps, and any other endpoints.
ASP.NET Core is a popular choice but is definitely not alone in the world of backend development. It is similar to other frameworks such as Laravel (PHP), Spring (Java), Ruby on Rails (Ruby), Django (Python), and others. Each has its own advantages and disadvantages. I chose ASP.NET Core for this book as it is one of the top frameworks out there, runs on the powerful C# language, and has wonderful IDE support.
The frontend is where users interact with your system. There's a lot to consider and prepare for in the frontend since users, unlike machines, are not homogeneous and this affects their experience when using a website—some have technical experience and some do not; some are young while others are older. The design should be inviting, the flow of work should be clear, and the way things work should help the user be effective and avoid mistakes.
We achieve these targets by working with three technologies that complement each other: HTML, Cascading Style Sheets (CSS), and JavaScript — the undisputed kings of the WWW:
HTML
: Describes what exists on a page
CSS
: Describes how a page looks
JavaScript
: Describes how a page behaves
These technologies have been the foundation of the internet almost since the day it was born. They have been growing and maturing ever since, adding much-needed features that enable more complex systems to be written on top of them.
As a result, frontend development frameworks have started to pop up in the last decade. Their goal is to take advantage of HTML, CSS, and JavaScript and bring them to the next level. These frameworks have added conventions, programming models, and advanced patterns and techniques, and have generally enabled developers to create massive systems using web technologies in a productive and stable way.
These advances indicated the beginning of a big shift in web development architecture—from traditional, server-centric architecture to Single-page application (SPA), client-server architecture.
Since the beginning of the WWW, the way web applications has been developed was server-centric, with minimal to no code running on the client. For example, the following sequence describes the usual flow of work:
The user browses to a web address.
The server gets the request, generates HTML for the user, and sends it back.
The browser gets the HTML and displays it to the user. The user sees the web page and clicks a button.
The server receives the button click, generates HTML that matches the button click, and returns it. In the meantime, the user sees an empty browser screen.
The browser gets the HTML and displays it to the user. The user sees the web page.
On the one hand, this was easier to code and maintain, since all the code was located on the server. On the other hand, this way is slow and provides a poor user experience for the user.
This architecture was used mainly because browsers didn't support features required for rich client development. Once that started to change with new versions of HTML, CSS, and JavaScript, the shift toward full client-server architecture began too.
The new architecture is known as SPA, which is basically client-server architecture. It was named SPA because of its differences from traditional web applications. In traditional web applications, the user navigates between different pages that are retrieved separately from the server upon request. In SPA applications, there is only one page, which contains the entire application, and every UI change is made locally via JavaScript. A usual flow of work in SPA architecture will look like the following:
The user navigates to a web address.
The server responds with HTML and multiple JavaScript files that contain the client-side application code.
The browser gets the files and displays the web page to the user. The user sees it and clicks a button.
JavaScript code on the client handles the click and calls the server side for data. In the meantime, the user sees a loading animation.
The server gets the request for data, retrieves the required data, and sends it back to the client.
JavaScript gets the response from the server, generates matching HTML, and displays it to the user. The user sees the updated web page.
This architecture enables rich client development that works quickly and smoothly. However, it does make it more complicated to develop web applications, as developers are required to master both client and server technologies.
Hypertext markup language (HTML) has been a part of web development since the very beginning of the WWW in 1989. At the beginning, it was used to display simple documents, but as the web grew, HTML matured and adjusted to support not just documents, but also full-blown applications.
HTML is a markup language, which means that it does not have programming language-specific dynamic capabilities such as variables, loops, or functions. Its sole responsibility is to statically describe the content of a web page.
The most recent version, HTML5, added long-awaited features such as new types of form controls, canvas, native video capabilities, and numerous new JavaScript APIs.
CSS is a style sheet language that is used to describe how HTML elements look. It is one of the pillars of web development, and provides many features for web developers that enable the creation of web applications that look great and adapt themselves to both mobile and desktop use.
CSS is a markup language and, like HTML, it does not support dynamic features such as variables and loops. Having said that, CSS does have some capabilities that enable it to change the look of an element based on its state, such as when a mouse is hovering over it, or based on an environment detail such as screen width.
In recent years, there has been interesting progress in the world of CSS. Since CSS is used in every single web application today, developers required more advanced capabilities for development — features such as variables, hierarchy, mixins (grouping CSS declarations for better reusability), and others — that were absent from CSS. As a result, new languages have been created, such as SCSS and LESS. These languages are supersets of CSS—they add much-needed features to the CSS development process and compile to CSS to be interpreted by browsers.
The last version of CSS, CSS3, added features such as web fonts, animations, transformations, and transitions that made the web application experience much smoother and more user-friendly.
JavaScript is the third part of the web development triangle — HTML, CSS, and JavaScript. It is a dynamic multi-paradigm programming language that is natively supported by all web browsers. It is used to add dynamic capabilities to web pages and to control the behavior of its elements.
The JavaScript language is an implementation of its standard, ECMAScript. Almost every browser has its own implementation of the ECMAScript standard. For example, Chrome has V8, Safari has WebKit, and Edge has Chakra.
JavaScript is the basis of all web application development frameworks, such as Angular, React, and others. Additionally, apart from frontend development, it has been adapted for backend development via the Node.js runtime environment.
The ES2015 version brought major enhancements to the language with new syntax for classes and modules, the for-of loop, arrow functions, and more. The latest version, ES2017, introduced the anticipated async/await feature.
TypeScript is a programming language developed by Microsoft, and is used primarily as a JavaScript substitute for development. The language adds features and enhancements to the JavaScript language that help in creating and maintaining large code bases.
TypeScript compiles (or, more correctly, transpiles) to JavaScript, which can then be interpreted by browsers or any other JavaScript runtime environments.
TypeScript adds static typing capabilities to JavaScript, such as type declaration and interfaces. In addition, it enables developers to use new JavaScript syntax from the latest, or even future, ECMAScript releases, and compile them to JavaScript, which can be interpreted by today's web browsers.
TypeScript has become very popular in the last couple of years, and is even used to develop the Angular framework itself. Though it is not required for SPA-based application development, it makes code clearer and more maintainable, which is why it is highly popular among developers.
Writing your frontend with pure JavaScript is possible, and it was the way websites were developed for many years. Over the years, several libraries have emerged incorporating different controls and allowing code reusability. As they have grown, some of these libraries have merged together to create a framework that helps developers to create complete websites from start to end, while also providing answers to many aspects required by modern websites, such as routing, authentication, data binding, state management, and so on.
In this book, we will concentrate on three of the most popular JavaScript frameworks today: Angular, React, and Vue.js.
Angular (https://angular.io/) is an SPA frontend web application development platform developed by Google and the open source community. It is the successor of the popular AngularJS framework, which dominated the SPA platform world at the beginning of the decade.
Angular takes HTML, CSS, and JavaScript and puts them in the context of application development with modular, component-based architecture, conventions, and utilities. It consists of a few basic concepts:
Modules
: Containers of Angular code
Data binding
: A mechanism that automatically reflects changes in the code on the UI, and vice versa
Components
: An HTML template combined with JavaScript code that controls it
Directives
: Add behavior to HTML elements of Angular components
Services
: Units of work that are additional to UI development, such as data handling or logging
