49,19 €
Web Applications with ASP.NET Core Blazor is a comprehensive guide to building modern web applications using the Blazor framework. It begins with an introduction to WebAssembly, detailing its purpose, history, and integration with JavaScript, followed by an exploration of Blazor's various hosting models, including Blazor Server, Blazor WebAssembly, and Blazor Hybrid.
The book covers essential Blazor components like Razor, directives, data binding, and event handling, and delves into advanced component techniques such as CSS isolation and component templating. Readers will also learn about file uploading, serving, and securing files within Blazor applications.
The text provides thorough insights into user input collection through forms, navigation in Blazor apps, and interop between .NET and JavaScript. Additionally, it explores HTTP communication, data persistence using EF Core, and security measures with Identity.
Finally, the book concludes with a deep dive into deploying Blazor applications using Docker and Kubernetes, including practical guidance on containerization and deploying on Azure. Designed for web developers and tech enthusiasts, this book equips readers with the knowledge to build robust, interactive web applications with ASP.NET Core Blazor.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 253
Veröffentlichungsjahr: 2024
WEB APPLICATIONSWITH ASP.NET CORE BLAZOR
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY
By purchasing or using this book and companion files (the “Work”), you agree that this license grants permission to use the contents contained herein, including the disc, but does not give you the right of ownership to any of the textual content in the book / disc or ownership to any of the information or products contained in it. This license does not permit uploading of the Work onto the Internet or on a network (of any kind) without the written consent of the Publisher. Duplication or dissemination of any text, code, simulations, images, etc. contained herein is limited to and subject to licensing terms for the respective products, and permission must be obtained from the Publisher or the owner of the content, etc., in order to reproduce or network any portion of the textual material (in any media) that is contained in the Work.
MERCURY LEARNING AND INFORMATION (“MLI” or “the Publisher”) and anyone involved in the creation, writing, or production of the companion disc, accompanying algorithms, code, or computer programs (“the software”), and any accompanying Web site or software of the Work, cannot and do not warrant the performance or results that might be obtained by using the contents of the Work. The author, developers, and the Publisher have used their best efforts to ensure the accuracy and functionality of the textual material and/or programs contained in this package; we, however, make no warranty of any kind, express or implied, regarding the performance of these contents or programs. The Work is sold “as is” without warranty (except for defective materials used in manufacturing the book or due to faulty workmanship).
The author, developers, and the publisher of any accompanying content, and anyone involved in the composition, production, and manufacturing of this work will not be liable for damages of any kind arising out of the use of (or the inability to use) the algorithms, source code, computer programs, or textual material contained in this publication. This includes, but is not limited to, loss of revenue or profit, or other incidental, physical, or consequential damages arising out of the use of this Work.
The sole remedy in the event of a claim of any kind is expressly limited to replacement of the book and/or files, and only at the discretion of the Publisher. The use of “implied warranty” and certain “exclusions” varies from state to state and might not apply to the purchaser of this product.
Companion files (sample code and figures) are available for downloading by writing to the publisher (with proof of purchase) at [email protected].
WEB APPLICATIONSWITH ASP.NET CORE BLAZOR
Create Powerful, Responsive, andEngaging Web Applications
Brian Ding
MERCURY LEARNINGAND INFORMATION
Boston, Massachusetts
Copyright ©2024 by MERCURY LEARNING AND INFORMATION.An Imprint of DeGruyter Inc. All rights reserved. Reprinted and revised with permission.
Original title and copyright: WEB APPLICATIONS WITH ASP.NET CORE BLAZOR.Copyright ©2023 by BPB Publications. All rights reserved. ISBN: 978-93-55518-798.
This publication, portions of it, or any accompanying software may not be reproduced in any way, stored in a retrieval system of any type, or transmitted by any means, media, electronic display, or mechanical display, including, but not limited to, photocopy, recording, Internet postings, or scanning, without prior permission in writing from the publisher.
Publisher: David Pallai
MERCURY LEARNINGAND INFORMATION
121 High Street, 3rd Floor
Boston, MA 02110
www.merclearning.com
800-232-0223
B. Ding. Web Applications with ASP.NET Core Blazor: Create Powerful, Responsive, and Engaging Web Applications.ISBN: 978-1-50152-267-3
The publisher recognizes and respects all marks used by companies, manufacturers, and developers as a means to distinguish their products. All brand names and product names mentioned in this book are trademarks or service marks of their respective companies. Any omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to infringe on the property of others.
Library of Congress Control Number: 2024939129
242526321 This book is printed on acid-free paper in the United States of America.
Our titles are available for adoption, license, or bulk purchase by institutions, corporations, etc. For additional information, please contact the Customer Service Dept. at 800-232-0223 (toll free).
All of our titles are available in digital format at academiccourseware.com and other digital vendors. Companion files (code samples and figures) are available for downloading (with proof of purchase)by writing to the publisher at [email protected]. The sole obligation of MERCURY LEARNINGAND INFORMATION to the purchaser is to replace the files, based on defective materials or faulty workmanship, but not based on the operation or functionality of the product.
TO
My beloved parents:
Zhong Ding,
Yi Hu,
&
My wife, Haoran Diao
CONTENTS
Preface
Acknowledgments
About the Author
About the Reviewer
Chapter 1: WebAssembly Introduction
Introduction
Structure
Objectives
What Is WebAssembly
History of WebAssembly
Hello World! with WebAssembly
Call WebAssembly from JavaScript
WebAssembly in the Future
Popular WebAssembly Languages
.NET Core
ASP.NET Core
When to Choose ASP.NET Core Blazor
Conclusion
Chapter 2: Choose Your Hosting Model
Introduction
Structure
Objectives
WebSocket
SignalR
Blazor Server
Blazor WebAssembly
Blazor Hybrid
Conclusion
Chapter 3: Implementing Razor and Other Components
Introduction
Structure
Objectives
Razor Components
Directive
Directive Attribute
One-Way Binding
Binding Event
Binding Format
Unparsed Value
Two-Way Binding
Cascading
Event Handling
Lifecycle
Layout
Libraries
Fast-Blazor
MatBlazor
Ant Design Blazor
BootstrapBlazor
Conclusion
Chapter 4: Advanced Techniques for Blazor Component Enhancement
Introduction
Structure
Component Reference
Components Preserving
Template Components
CSS Isolation
Conclusion
Chapter 5: File Uploading in Blazor
Introduction
Structure
Objectives
Build Comments for EShop
File Transfer
File Upload
Tips
Conclusion
Chapter 6: Serving and Securing Files in Blazor
Introduction
Structure
Objectives
Middleware
Serve Static Files
Serve Dynamic Files
Security Advice
Conclusion
Chapter 7: Collecting User Input with Forms
Introduction
Structure
Objectives
Forms
EditForm
InputBase
Validation
Custom Validation
Form Submission
EditContext and Form State
Conclusion
Chapter 8: Navigating Over Application
Introduction
Structure
Objectives
Router
RouteAttribute
NavLink
Route Parameters
Navigation Events and Asynchronous Navigation
ASP.NET Core Integration
Conclusion
Chapter 9: .NET and JavaScript Interop
Introduction
Structure
Objectives
Serialization
Loading JavaScript
Initializer
Calling JavaScript from .NET
JavaScript Isolation
Calling .NET from JavaScript
Cache
Element Reference
Type Safety
Conclusion
Chapter 10: Connecting to the World with HTTP
Introduction
Structure
Objectives
Front-End and Back-End Separation
HTTP Protocol
Cross-Origin Resource Sharing
HTTPClient
HTTPClientFactory
HTTPClient Again
gRPC
Conclusion
Chapter 11: Data Persistence with EF Core
Introduction
Structure
Objectives
Stateless and Stateful
EntityFramework Core
Context Object
Data Entities
Database Migration
Data Update
Data Query
Conclusion
Chapter 12: Protecting Your Application with Identity
Introduction
Structure
Objectives
Authentication
AuthenticationStateProvider
Authorization
Role-Based Authorization
Policy-Based Authorization
ASP.NET Core Identity
Conclusion
Chapter 13: Deploying with Docker and Kubernetes
Introduction
Structure
Objectives
What Is Docker?
Building a Docker Image
Image Layer
What Is K8S?
K8S Components
Deploy to AKS—K8S on Azure
Conclusion
Index
PREFACE
This book covers many different aspects of developing Blazor applications, a modern way to build rich UI web applications. The book introduces how to leverage .NET and its eco-systems to build a modern enterprise application. It introduces WebAssembly and how it enables web applications to be written in any programming language. It also compares different Blazor hosting models and the strategy to select a model that suits its business requirements. The book is designed for web developers, software engineers, and tech enthusiasts looking to build robust, interactive web applications using ASP.NET Core Blazor.
Using a demonstrative approach for Blazor learners, every chapter includes numerous code examples and a Blazor source code analysis. It covers basic Blazor directives and components and how these concepts can be combined together to build a more complex customized component. This book also explains some advanced techniques to control component rendering and improve performance.
The book is divided into 13 chapters. It begins with the introduction of WebAssembly and covers the basic concepts in Blazor Framework. It includes some advanced techniques you may find handy when developing production-ready applications, as well as explaining source code structures and designing patterns and styles. So, readers can learn the basics of how a Blazor application is running. The chapter details are listed below.
Chapter 1: WebAssembly Introduction
Discover the power of WebAssembly and why it was introduced despite the capabilities of JavaScript. This chapter includes a hands-on demonstration of compiling C/C++ source code into WebAssembly and calling WebAssembly functions from JavaScript. It also explores the WASM binary format, various sections of the binary code, and popular languages that produce WebAssembly modules, including ASP.NET Core Blazor.
Chapter 2: Choosing Your Hosting Model
Learn about WebSocket and compare it to HTTP. Explore SignalR, a .NET library that implements WebSocket with a fallback to long polling for compatibility. Understand the basic structure of a Blazor application and compare three Blazor hosting models: Blazor Server, Blazor WebAssembly, and Blazor Hybrid.
Chapter 3: Implementing Razor and Other Components
Explore the basic components of Blazor applications, including directives, binding, cascading, and event handling. This chapter explains the lifecycle of a typical component and introduces layouts, a special component type useful for building applications with multiple functional spaces. Discover popular third-party libraries for building enterprise applications.
Chapter 4: Advanced Techniques for Blazor Component Enhancement
This chapter discusses advanced component features and source code. Learn how to reference, preserve, and template components, and how to define a CSS style specific to a component using CSS isolation.
Chapter 5: File Uploading in Blazor
Understand common file transfer protocols and their differences. Learn about the component used to upload files in the Blazor framework, complete with source code explanations and detailed usage examples.
Chapter 6: Serving and Securing Files in Blazor
Gain insights into one of the most important mechanisms in ASP.NET Core: middlewares. Learn how middlewares handle client requests, serve static and dynamic files in Blazor, and apply basic security rules to protect servers from attacks.
Chapter 7: Collecting User Input with Forms
Master web forms, which are essential for data input from application users. This chapter covers default data validation, customizing validation rules and error prompts, and key events and concepts in Blazor forms, including submission, context, and state.
Chapter 8: Navigating Over Applications
Explore page navigation in a Blazor application. Understand the key routing components in the Blazor framework, different types of routing with parameters, navigation events, and asynchronous navigation for enterprise-level applications.
Chapter 9: .NET and JavaScript Interop
Learn about serialization and deserialization with JSON for communication between web services, and its application in .NET and JavaScript interop. This chapter covers loading customized JavaScript code, calling JavaScript from .NET and vice versa, and advanced interop topics such as cache, element reference, and type safety.
Chapter 10: Connecting to the World with HTTP
Discover the HTTP protocol, its role in front-end and back-end separation, and the challenges of CORS. This chapter explains the built-in types HttpClient and HttpClientFactory for external communication and covers RPC and gRPC with practical examples.
Chapter 11: Data Persistence with EF Core
Explore data persistence using EntityFramework Core, comparing stateless and stateful concepts. Understand the design ideas behind EF Core and analyze its source code to learn patterns supporting various databases. Key concepts such as entity, context, query, and migration are explained with detailed examples.
Chapter 12: Protecting Your Application with Identity
Learn about authentication and authorization in Blazor applications. This chapter covers the authentication mechanism, the AuthenticationStateProvider source code for customized authentication, and different authorization approaches, including role-based and policy-based authorizations, with code examples.
Chapter 13: Deploying with Docker and Kubernetes
Master modern deployment techniques using Docker and Kubernetes. Learn how to containerize Blazor applications and deploy them using Azure Kubernetes Services and Azure Container Registry.
Companion files with code samples and color figures from the book are available for downloading by writing [email protected].
Transform your web development skills with ASP.NET Core Blazor. Successful coding!
ACKNOWLEDGMENTS
This book would not exist without the help of many people, mostly including the continuous support from my parents and my wife's encouragement for writing the book. They've taken most of the housework so that I can focus on writing it — I could have never completed this book without their support. My gratitude also goes to the team at my publisher for being supportive enough to provide me with quite a long time to finish the book. This is my first book ever, and I would like to thank them for their professionalism, guidance, and patience along the way.
ABOUT THE AUTHOR
Brian Ding has over 8 years of experience in TypeScript and .NET development, specializing in areas such as WinForm, WPF, ASP.NET, and ASP.NET Core. Currently employed at BMW Archermind Information Technology Co. Ltd., he holds the position of tech leader, where he focuses on creating engaging digital driving experiences for BMW customers. Throughout his career, Brian has worked in diverse domains including software development, DevOps, automation tools, and cloud technologies. His passion lies in coding and developing scalable solutions that are adaptable and easy to maintain.
ABOUT THE REVIEWER
Trilok Sharma is a seasoned technical architect with 14 years of expertise in designing, developing, and implementing enterprise-level solutions on the Microsoft technology stack. Throughout his career, Trilok Sharma has demonstrated mastery in Microsoft technologies, including Blazor Server, Blazor Web Assembly (WASM), .Net 7.0, Net Core, C#, Angular, React, SQL Server, Azure, and AWS. He has a strong command over object-oriented programming principles and has leveraged their knowledge to architect scalable and efficient applications. Trilok holds a bachelor’s degree in computer science and MBA in Project +IT Management. With his strong technical understanding, attention to detail, and commitment to quality, Trilok Sharma continues to make valuable contributions as a technical reviewer in the Microsoft technology space.
CHAPTER 1
WEBASSEMBLY INTRODUCTION
INTRODUCTION
This chapter introduces the concept and roadmap of WebAssembly and how it enables Web applications to be written in any programming language. It also discusses a few popular WebAssembly languages and illustrates the benefits of building a Web application with ASP.NET Core Blazor.
STRUCTURE
This chapter discusses the following topics:
■What is WebAssembly?
■How is a WebAssembly module compiled?
■What does a WebAssembly module look like?
■What is .NET Core with WebAssembly?
OBJECTIVES
This chapter is intended to guide readers briefly through the world of WebAssembly, get familiar with WebAssembly modules, and explain how .NET Core is involved with WebAssembly. Readers will learn how to install Emscripten SDK and will also get familiar with emcc command. The chapter will explore the world of WebAssembly binary format and help readers understand how a module was constructed. Finally, the chapter will introduce the new generation of .NET—.NET Core with the WebAssembly framework, ASP. NET Core Blazor.
WHAT IS WEBASSEMBLY
WebAssembly (abbreviated as Wasm) is a target for modern languages for compilation of more than one language, designed to be highly efficient while maintaining a safe sandbox environment. The definition seems to be too official. When broken down into two words Web and Assembly, one might get a better understanding of WebAssembly. Web is a familiar word to most in this era of prevalent Internet use. For example, people can buy goods from Amazon.com, watch videos on Youtube.com, and check out how friends’ lives are on Facebook.com.
Assembly, however, might not be that obvious to those who do not work with computer science. In recent years, most developers write programs with advanced programming languages like Golang,C#, or Java. Prior to using advanced languages, programmers used to write code with Assembly, which is more specific to the hardware platform. For example, writing Assembly code for x86 CPU and ARM CPU will have different key words and syntax. As a language that is closer to the hardware level, Assembly language usually has higher runtime efficiency than advanced languages.
HISTORY OF WEBASSEMBLY
The first Web was created in the early 1990s. At that time, the Web was mainly used by scientists to share information. The Web was designed to be the media of static content. HTML defines the content. URL locates the resources on the World Wide Web. The client (browser) would then send a HTTP request to the server through a URL and then render the HTML content returned by the server. In this process, all the information transported was static, and that means there was no way that a user could interact with the Web.
In 1995, Branden Eich designed a new language called JavaScript in only ten days. It looks like Java, but is easier to use than Java, and even nonprofessional Web site workers can understand it. Eich seemed to dislike JavaScript. He was of the belief that everything that is excellent is not original, and everything original is not excellent. With Chrome getting more popular, JavaScript soon appeared everywhere on the Web. Currently, Engine V8 from Google is enabling JavaScript to be used in large and complex projects.
HELLO WORLD! WITH WEBASSEMBLY
JavaScript has been efficient, then why create another “Assembly Language” for the Web? JavaScript is a dynamic language, which means the type of variable could be changed in runtime, unlike C# or Java. For programmers or developers, it is very convenient to write code, but it becomes cumbersome when it comes to the interpreter. The interpreter must judge which type of variable is being used while running code. Even armed with JIT compiler, compiling JavaScript into machine code sometimes requires it to be rolled back to the original code under some circumstances. For this reason, many companies that build browsers are looking for a more performance-enhanced solution.
In April 2015, the WebAssembly Community Group was founded. Two years later, WebAssembly became one of the W3C standards. In 2019, WebAssembly became one of the standard Web languages, along with HTML, CSS, and JavaScript. Through the years, most of the popular Web browsers have supported WebAssembly.
Many languages, for example, C/C++, C#, and Go can now be compiled to WebAssembly.
Using C/C++ as an example, write a simple C++ program that says Hello World. Save it as hello.cpp under my-hello-world-demo:
#include <stdio.h>
int main() {
printf("Hello World!\n");
}
Emscripten SDK is an open-source SDK that compiles C/C++ to WebAssembly, and auto-generates JavaScript code that can run the .wasm file. Install the SDK following the instructions here https://emscripten.org/docs/getting_started/downloads.html and compile the code with the following command:
emcc hello.cpp -o hello.html
There will be three output files, hello.html, hello.js and hello.wasm, shown as follows:
my-hello-world-demo
├───hello.cpp
└───hello.html
└───hello.js
└───hello.wasm
hello.html is the default Web page, and hello.js is the code logic running on it, designed by the Emscripten SDK.
Next, install Python from https://www.python.org. Open the command line or terminal and move to my-hello-world-demo and enter python -m http.server, Python will start a server listening on port 8000. Open the browser and navigate to http://localhost:8000, it will show the files under my-hello-world-demo, then click hello.html, a default front-end page provided by emscripten will show. Refer to Figure 1.1.
FIGURE 1.1 Default front-end Web page.
In the black box area, it shows Hello World! that we printed. A program that is running the C++ code. If we open the DevTools and switch to Console Tab, Hello World! is also printed there.
CALL WEBASSEMBLY FROM JAVASCRIPT
WEBASSEMBLY IN THE FUTURE
In the future, it is likely that anything that can possibly be compiled targeting WebAssembly, eventually, will be compiled to WebAssembly. WebAssembly was designed for the Web initially, but it is not limited to the Web; it could be running on the server as well. There is a possibility that one day in the future, all computing units will be running WebAssembly, regardless of the selected language, both for the client side and the server side.
POPULAR WEBASSEMBLY LANGUAGES
Many popular languages have been supported; for example, C/C++, Rust, C#, Golang, and many more. Some of these supports are still experimental. Alternatively, some have been used in a production environment for a long time. This book uses C#, and experienced users will find building a WebAssembly application with C# will be a very smooth process. For inexperienced C# users the book will cover all the knowledge and concepts needed.
.NET CORE
In the 2000s, .NET Framework was born. It is a reaction from Microsoft to the world of Java. The initial name was