Page
1
(This page has no text content)
Page
2
Web Development with Blazor Fourth Edition A practical guide to building interactive UIs with C# 14 and .NET 10 Jimmy Engström
Page
3
Web Development with Blazor Fourth Edition Copyright © 2026 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. Portfolio Director: Ashwin Nair Portfolio Manager: Nitin Nainani Project Manager: Ruvika Rao Content Engineer: Adrija Mitra Technical Editor: Rohit Singh Indexer: Manju Arasan Proofreader: Adrija Mitra Production Designer: Prashant Ghare Growth Lead: Anamika Singh First Published: June 2021 Second Edition: March 2023 Third Edition: April 2024 Fourth Edition: June 2026 Production reference: 1080626 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul's Square Birmingham B3 1RB, UK. ISBN 978-1-80611-289-0 www.packtpub.com
Page
4
I dedicate this book to my mom and dad, who gave me my first computer and encouraged my curiosity without knowing it would shape the rest of my life. Without your support and encouragement, I would never have started this journey. To my brother, who patiently taught me how to code and helped turn that curiosity into a passion that would eventually become my career. Thank you for taking the time to share your knowledge and inspire me to keep learning. To my sister, who helped me with my English homework growing up. Without that help, my life would probably have looked very different. Knowing English has allowed me to travel the world, speak internationally, and make friends from all over the globe. And most of all, to my wife, Jessica. Thank you for your endless support, encouragement, patience, and for always believing in me, even during the late nights, deadlines, and stressful moments. I love you. None of this would have been possible without you. Thank you to everyone who helped review this book and make it better. – Jimmy Engström Since my parents don't know English very well, I would like to add this in Swedish as well. Jag dedikerar den här boken till min mamma och pappa, som gav mig min första dator och uppmuntrade min nyfikenhet utan att veta att det skulle forma resten av mitt liv. Utan ert stöd och er uppmuntran hade jag aldrig påbörjat den här resan. Till min bror, som tålmodigt lärde mig att koda och hjälpte mig att förvandla den nyfikenheten till en passion som till slut blev min karriär. Tack för att du tog dig tiden att dela med dig av din kunskap och inspirera mig att fortsätta lära mig. Till min syster, som hjälpte mig med engelskaläxorna när jag växte upp. Utan den hjälpen hade mitt liv förmodligen sett väldigt annorlunda ut. Tack vare engelskan har jag fått möjlighet att resa världen över, tala internationellt och få vänner från hela världen. Och framför allt till min fru Jessica. Tack för ditt oändliga stöd, ditt tålamod, din uppmuntran och för att du alltid trott på mig, även under sena kvällar, deadlines och stressiga stunder. Jag älskar dig. Det här hade aldrig varit möjligt utan dig. Tack också till alla som hjälpt till att granska boken och gjort den bättre. – Jimmy Engström
Page
5
Foreword When we first set out to build Blazor, the goal was simple to describe and challenging to achieve: enable developers to build rich, interactive web applications using the language, tools, and platform they already know and love, without sacrificing the capabilities of the web. In the years since, Blazor has grown from an ambitious experiment into a core part of modern web development with .NET. Just as importantly, a vibrant community of developers, educators, and contributors has grown alongside it. This book, now in its fourth edition, is one of the best examples of that community at work. I've had the pleasure of knowing Jimmy for many years, and there are few people who combine deep technical expertise with genuine enthusiasm the way he does. Jimmy understands deeply how Blazor works and has extensive real-world experience using Blazor for production applications. He's also a talented teacher and educator. He takes concepts that can seem complex at first and presents them through practical, approachable examples that help developers build confidence as they learn. Whether you're encountering Blazor for the first time or looking to deepen your existing knowledge, that ability to teach through real-world experience makes a tremendous difference. What makes this fourth edition especially valuable is how closely it follows the evolution of Blazor and modern web development. Today's Blazor applications can render on the server, run in the browser through WebAssembly, or combine multiple rendering approaches within a single application. Developers have more flexibility than ever to choose the right model for each scenario. Keeping pace with that evolution is no small task, and Jimmy has done the hard work of ensuring that readers are learning the current state of the platform and the patterns that matter today. The broader .NET ecosystem has evolved as well. Modern web applications rarely exist in isolation. They interact with APIs, databases, caches, cloud services, and increasingly complex distributed systems. At the same time, developers are expected to move quickly while maintaining reliability and visibility into how their applications behave. Tools such as Aspire help address these challenges by making it easier to develop, run, and observe multi-service applications. Throughout this edition, Jimmy incorporates modern practices and tooling that reflect how real applications are built, helping readers move beyond individual components and toward complete, production-ready solutions.
Page
6
Whether you're building your first Blazor application or looking to sharpen your skills with the latest capabilities, you're in excellent hands. Jimmy will guide you from the fundamentals through the modern techniques, tools, and patterns that make Blazor such a productive and enjoyable platform for building web applications. Read it, build with it, experiment, and most importantly, enjoy the process. Welcome to Blazor. I can't wait to see what you build! Daniel Roth Principal Product Manager, ASP.NET Core and Blazor Microsoft
Page
7
Contributors About the author Jimmy Engström has been programming since he was 7 years old and got his first computer. He loves staying on the cutting edge of technology and trying new things. When he first discovered Blazor, he immediately saw its potential and adopted it while it was still in beta. He has been running Blazor in production since Microsoft launched it. His passion for the .NET industry and community has taken him around the world, speaking about development and sharing knowledge with other developers. Microsoft has recognized this passion by awarding him the Microsoft Most Valuable Professional (MVP) award 12 years in a row. Jimmy was named Educator of the Year 2025 for his contributions to the developer community. He is also an instructor on Dometrain, where he creates video courses focused on .NET and Blazor development. In addition to writing books, Jimmy is an international speaker, content creator, and host of the Coding After Work podcast and YouTube channel, where he talks with developers and technology leaders from around the world.
Page
8
About the reviewers Stacy Cashmore has been developing solutions since the mid-1990s in various companies and industries, ranging from facilitating contract jobbing to allowing consumers to close a mortgage without the help of a financial adviser, with lots in between. She has a passion for sharing knowledge, using storytelling to share her experiences to help teams grow in the ways they develop software and work together, and performing live coding demonstrations to inspire others to try new technologies. In 2022, Stacy published her first book, aimed at helping developers get started building dynamic applications using C#, Azure Functions, and Azure Static Web Apps. In February 2026, she released the second edition, updated for .NET 9 and with added infrastructure-as-code content to help readers apply what they've learned in real-world scenarios. For her efforts in the community, Stacy has been awarded the Microsoft MVP for Developer Technologies since 2020. Mabrouk Mahdhi is a Principal Software Engineer and a recognized Microsoft MVP in .NET technologies. He specializes in modern .NET development, with deep expertise in Blazor, ASP.NET Core, and .NET MAUI, building scalable web applications, enterprise APIs, and high- performance, data-driven systems. He is the founder and organizer of Tunisia Dev Days, one of the largest .NET and software engineering conferences in North Africa, bringing together developers, architects, and technology leaders to discuss innovation, AI, cloud computing, and modern software engineering practices.
Page
9
Moien Tajik is a Principal Software Engineer at AIHR in the Netherlands, with experience leading engineering teams across both B2C and B2B domains. Previously a Technical Fellow at Alibaba Travels Company, he has deep expertise across the .NET ecosystem, from backend to frontend, and has designed and scaled systems with different architectures, including microservices, modular monoliths, and cloud and on-premise deployments. He brings a strong foundation in software architecture, distributed systems, and technical leadership, with a track record of delivering robust, scalable solutions. Moien is passionate about technology, product innovation, AI, and engineering excellence. Eder Bragança Pereira is a computer scientist and a software engineer focused on JavaScript. He is passionate about technology and works on building web applications, while also exploring game development as an area of growing interest.
Page
10
Table of Contents Preface xxiii Free benefits with your book ............................................................................ xxix Part 1: Getting Started with Blazor 1 Chapter 1: Hello Blazor 3 Technical requirements ........................................................................................ 4 How Blazor was created ........................................................................................ 4 Why Blazor? ......................................................................................................... 6 Preceding Blazor .................................................................................................. 7 Introducing WebAssembly .................................................................................... 8 Introducing .NET ............................................................................................... 10 Summary ............................................................................................................ 12 Further reading ................................................................................................... 12 Learn more on Discord ......................................................................................... 12 Chapter 2: Creating Your First Blazor App 13 Technical requirements ....................................................................................... 13 Setting up your development environment .......................................................... 14 Windows • 14 macOS and Linux (or Windows) • 15 Installing Docker • 16 Creating our first Blazor application .................................................................... 17 Exploring the templates • 17 Blazor Web App template • 18 Blazor WebAssembly Standalone App template • 18 Creating a Blazor web application • 19 Introducing the .NET CLI .................................................................................... 23
Page
11
Figuring out the project structure ....................................................................... 24 Program.cs (BlazorWebApp project) • 24 Program.cs (BlazorWebApp.Client) • 27 App (BlazorWebApp) • 28 Routes • 29 Main layout • 30 NavMenu • 31 CSS • 32 Summary ........................................................................................................... 33 Chapter 3: Exploring Render Modes 35 Technical requirements ...................................................................................... 36 Running the WebAppTest project ........................................................................ 36 Understanding Server-Side Rendering (SSR) ....................................................... 37 Static SSR • 37 Testing static SSR • 39 Streaming SSR • 40 Testing streaming SSR • 42 Enhanced navigation • 42 Delving into the Blazor Server / Interactive Server ............................................... 43 Benefits of Blazor Server • 44 Downsides of Blazor Server • 45 Testing the render mode • 45 Real-world usage • 46 Exploring Blazor WebAssembly / Interactive WebAssembly ................................. 46 Benefits of Blazor WebAssembly • 48 Downsides of Blazor WebAssembly • 48 Testing the render mode • 48 Real-world notes • 49 Understanding Auto / Interactive Auto ................................................................ 49 Understanding where to put interactivity ........................................................... 50 Global • 50 Table of Contents x
Page
12
Per component (or page) • 50 What should you choose? • 51 Summary ............................................................................................................ 51 Chapter 4: Uncovering Aspire 53 Technical requirements ...................................................................................... 53 What is Aspire? ................................................................................................... 54 Why use Aspire? ................................................................................................. 55 Project structure ................................................................................................ 56 AppHost project • 56 ServiceDefaults project • 57 BlazorWebApp and BlazorWebApp.Client • 57 References and wiring • 57 The big picture • 57 Unraveling the Aspire Community Toolkit .......................................................... 58 What is it? • 58 Examples of community resources • 58 Exploring the Aspire dashboard .......................................................................... 59 Exploring logs, traces, and metrics ...................................................................... 60 Structured logs • 60 Traces • 61 Metrics • 61 Correlated logs • 62 Summary ........................................................................................................... 62 Learn more on Discord ........................................................................................ 63 Part 2: Building a Blazor Application 65 Chapter 5: Managing State – Part 1 67 Technical requirements ...................................................................................... 68 Creating data classes .......................................................................................... 68 Creating an interface and models ........................................................................ 73 xi Table of Contents
Page
13
Creating the repository ....................................................................................... 76 Adding the repository and database .................................................................... 86 Adding PostgreSQL • 86 Configuring the database and repository • 88 Exploring pgAdmin • 91 Summary ........................................................................................................... 93 Chapter 6: Understanding Basic Blazor Components 95 Technical requirements ...................................................................................... 95 Exploring components ....................................................................................... 96 Counter • 96 Weather • 98 Learning Razor syntax ....................................................................................... 101 Razor code blocks • 102 Implicit Razor expressions • 103 Explicit Razor expressions • 103 Expression encoding • 103 Directives • 104 Adding an attribute • 104 Adding an interface • 105 Inheriting • 105 Generics • 105 Changing the layout • 106 Setting a namespace • 106 Setting a route • 106 Adding a using statement • 106 Understanding dependency injection ................................................................. 107 Singleton • 108 Scoped • 109 Transient • 110 Injecting the service • 110 Changing the render mode • 111 Table of Contents xii
Page
14
Coming from an old template • 112 Figuring out where to put the code .................................................................... 113 In the Razor file • 114 In a partial class • 114 Inheriting a class • 115 Only code • 116 Exploring lifecycle events .................................................................................. 117 OnInitialized and OnInitializedAsync • 117 OnParametersSet and OnParametersSetAsync • 118 OnAfterRender and OnAfterRenderAsync • 118 ShouldRender • 118 Understanding parameters ................................................................................ 118 Cascading parameters • 119 Writing our first component ............................................................................. 120 Summary .......................................................................................................... 125 Chapter 7: Creating Advanced Blazor Components 127 Technical requirements ..................................................................................... 127 Exploring binding ............................................................................................. 128 One-way binding • 128 Two-way binding • 130 Diving into Actions and EventCallback ............................................................... 131 Using RenderFragment ...................................................................................... 133 ChildContent • 134 Building an alert component • 134 Designing components for real-world use • 137 Exploring the new built-in components ............................................................. 138 Setting the focus of the UI • 138 Influencing the HTML head • 139 Component virtualization • 143 Error boundaries • 145 Sections • 146 xiii Table of Contents
Page
15
Summary ......................................................................................................... 148 Chapter 8: Building Forms with Validation 149 Technical requirements ..................................................................................... 149 Exploring form elements ................................................................................... 149 EditForm • 150 InputBase<> • 152 InputCheckbox • 152 InputDate • 152 InputNumber • 152 InputSelect • 152 InputText • 152 InputTextArea • 152 InputRadio • 153 InputRadioGroup • 153 InputFile • 153 Adding validation .............................................................................................. 153 ValidationMessage • 155 ValidationSummary • 156 Custom validation class attributes ..................................................................... 156 Looking at bindings .......................................................................................... 160 Binding to HTML elements • 160 Binding to components • 161 Building an admin interface ............................................................................... 162 Listing and editing categories • 164 Listing and editing tags • 168 Listing and editing blog posts • 171 Why use an abstraction layer for your components • 180 Adding shared components • 181 Creating a button component • 184 Locking the navigation • 189 Summary .......................................................................................................... 192 Table of Contents xiv
Page
16
Learn more on Discord ....................................................................................... 193 Chapter 9: Creating an API 195 Technical requirements ..................................................................................... 195 Creating the service ........................................................................................... 195 Learning about Minimal APIs • 196 Adding the API controllers • 197 Adding APIs for handling blog posts • 197 Adding APIs for handling categories • 200 Adding APIs for handling tags • 202 Adding APIs for handling comments • 203 Creating the client ............................................................................................ 204 Summary ......................................................................................................... 208 Chapter 10: Adding Authentication and Authorization 211 Technical requirements ..................................................................................... 212 Setting up authentication .................................................................................. 212 Setting up Auth0 • 212 Configuring our Blazor app • 215 Securing our Blazor app ..................................................................................... 218 Securing Blazor WebAssembly .......................................................................... 220 Configuring the client application • 220 Running the application • 221 Adding roles ..................................................................................................... 222 Configuring Auth0 by adding roles • 222 Adding roles to Blazor • 223 Summary ......................................................................................................... 224 Chapter 11: Sharing Code and Resources 227 Technical requirements ..................................................................................... 227 Adding static files ............................................................................................. 228 Choosing between frameworks • 229 xv Table of Contents
Page
17
Adding a new style • 229 Adding CSS • 230 Making the admin interface more usable • 231 Making the menu more useful • 232 Making the blog look like a blog • 233 CSS isolation .................................................................................................... 235 Fixing the background • 237 Summary ......................................................................................................... 238 Chapter 12: JavaScript Interop 241 Technical requirements ..................................................................................... 241 Why do we need JavaScript? .............................................................................. 242 .NET to JavaScript ............................................................................................ 242 Global JavaScript (the old way) • 243 Collocated JavaScript • 243 JavaScript to .NET ............................................................................................ 247 Static .NET method call • 247 Instance method call • 248 Implementing an existing JavaScript library ...................................................... 251 JavaScript interop in WebAssembly .................................................................... 257 .NET to JavaScript • 257 JavaScript to .NET • 258 Summary ......................................................................................................... 260 Learn more on Discord ....................................................................................... 261 Chapter 13: Managing State – Part 2 263 Technical requirements .................................................................................... 264 Persistent component state ............................................................................... 264 Storing data on the server side .......................................................................... 267 Storing data in the URL ..................................................................................... 268 Route constraints • 268 Using a query string • 269 Table of Contents xvi
Page
18
Implementing browser storage ......................................................................... 270 Implementing session storage • 270 Implementing the shared code • 272 Using an in-memory state container service ....................................................... 275 Implementing real-time updates on InteractiveServer • 275 Implementing real-time updates on Blazor WebAssembly • 279 State management frameworks • 282 Root-level cascading values .............................................................................. 283 Summary ......................................................................................................... 284 Part 3: Running Blazor with Confidence 287 Chapter 14: Debugging the Code 289 Technical requirements .................................................................................... 289 Making things break ......................................................................................... 290 Debugging Blazor Server .................................................................................. 290 Debugging Blazor WebAssembly ....................................................................... 292 Debugging Blazor WebAssembly in the web browser ......................................... 293 Hot Reload ....................................................................................................... 294 Summary ......................................................................................................... 296 Chapter 15: Exploring Tracing and Metrics 297 Technical requirements .................................................................................... 297 Blazor Server metrics and tracing ..................................................................... 298 Enabling metrics and tracing • 299 What the metrics tell us • 299 Tracing in Blazor • 300 Blazor WebAssembly diagnostics ...................................................................... 302 Browser developer tools diagnostics • 303 WebAssembly Event Pipe diagnostics • 306 Collecting CPU samples • 308 Collecting runtime metrics • 310 xvii Table of Contents
Page
19
Collecting a GC dump • 313 Summary .......................................................................................................... 315 Chapter 16: Testing 317 Technical requirements ..................................................................................... 318 What is bUnit? .................................................................................................. 318 Setting up a test project ..................................................................................... 319 Mocking the API ............................................................................................... 322 Writing tests ..................................................................................................... 327 Authentication • 329 Testing JavaScript • 331 Blazm extension ................................................................................................ 333 Summary .......................................................................................................... 335 Learn more on Discord ....................................................................................... 335 Chapter 17: Deploy to Production 337 Technical requirements ..................................................................................... 337 Continuous delivery options .............................................................................. 337 Additional deployment resources • 339 Hosting options ................................................................................................ 339 Hosting Blazor Server/InteractiveServer • 339 Hosting InteractiveWebAssembly • 339 Hosting Blazor WebAssembly Standalone • 340 Hosting on IIS • 340 Summary ......................................................................................................... 340 Part 4: Going Beyond the Main Application 343 Chapter 18: Moving From, or Combining, an Existing Site 345 Technical requirements .................................................................................... 346 Introducing web components ........................................................................... 346 Exploring custom elements .............................................................................. 347 Table of Contents xviii
Page
20
Exploring the Blazor component ....................................................................... 347 Adding Blazor to an Angular site ........................................................................ 351 Adding Blazor to a React site .............................................................................. 352 Adding Blazor to MVC/Razor Pages .................................................................... 353 Adding web components to a Blazor site ............................................................ 355 Migrating from Web Forms ................................................................................ 357 Summary ......................................................................................................... 358 Chapter 19: Going Deeper into WebAssembly 361 Technical requirements .................................................................................... 362 Exploring the WebAssembly template ............................................................... 362 .NET WebAssembly build tools ......................................................................... 364 AOT compilation .............................................................................................. 364 WebAssembly Single Instruction, Multiple Data (SIMD) .................................... 365 Trimming ........................................................................................................ 366 Lazy loading ..................................................................................................... 366 Progressive web apps ........................................................................................ 369 Native dependencies ......................................................................................... 370 Common problems ............................................................................................ 372 Progress indicators • 372 Prerendering • 372 Summary .......................................................................................................... 373 Chapter 20: Examining Source Generators 375 Technical requirements ..................................................................................... 375 What a source generator is ................................................................................. 375 How to get started with source generators ........................................................ 378 Community projects ......................................................................................... 380 AutomaticInterface • 381 Blazorators • 381 C# source generators • 381 Roslyn SDK samples • 381 xix Table of Contents