Introduction to Blazor: Welcome to C# on the Web
8 min read
Welcome, developer! 🚀
If you have ever stared at a massive JavaScript codebase, sighed deeply, and wished you could just write the type-safe, structured C# code you love on the server... and run it in the browser? Well, stop wishing. It's here.
This guide explores Blazor, Microsoft’s solution to the Single Page Application (SPA) wars. We are going to cover why it exists, how it works under the hood, and how the modern .NET 8+ architecture changes the game.
1. What is Blazor? The Motivation and Possibilities
The Problem: The "JavaScript Monopoly"
For nearly two decades, if you wanted to run code in a user's browser, you had exactly one option: JavaScript (and eventually TypeScript).
Even if your backend was a robust, architecturally sound .NET API, your frontend had to be React, Angular, or Vue. This created the "Context Switch Tax":
- Duplication: You define a
Usermodel in C# on the server. You have to redefine that same interface in TypeScript on the client. - Mental Gymnastics: Switching between C# LINQ and JS Array methods.
- Tooling Gaps: Losing the raw power of Visual Studio’s debugging when moving to the browser.
The Solution: Blazor
Blazor is a web UI framework that enables you to write client-side web UI using C# instead of JavaScript.
- Definition: Blazor allows you to build interactive web UIs using C# and HTML. It uses the Razor syntax (a mix of HTML and C#) to render views.
- The Killer Feature: Because both client and server are .NET, you can share code (libraries, models, validation logic) across the entire stack.
Industry Reality:
In the enterprise world, Blazor is rapidly replacing legacy ASP.NET Web Forms and MVC apps because teams don't need to hire a separate React specialist. They can use their existing C# workforce.
Fun Fact: The name "Blazor" is a portmanteau of "Browser" and "Razor". It started as an experimental project by Steve Sanderson (the creator of Knockout.js) who famously demoed .NET running in a browser at a conference, blowing everyone’s mind.
2. Hosting Models Explained: Server vs. WebAssembly
To understand modern Blazor, you must understand the two distinct ways it used to run. These are now "Render Modes" in .NET 8, but the physics behind them remain the same.
A. Blazor Server
The Problem
You want your app to load instantly and have full access to server resources (databases, secrets) without exposing them to the client.
The Solution
The app logic runs entirely on the Server.
- The user visits the site.
- The browser downloads a small JavaScript file (
blazor.server.js). - This script opens a real-time SignalR (WebSocket) connection to the server.
- When a user clicks a button, the click event is sent to the server.
- The server processes the C# code, calculates the UI changes (DOM diff), and sends only the changes back to the browser to repaint.
- Pros: Instant load time (no heavy DLL download), code stays safe on server.
- Cons: No offline support. If the internet flickers, the app freezes ("Reconnecting..."). High latency creates UI lag.
B. Blazor WebAssembly (Wasm)
The Problem
You want a true Single Page Application (like React) that runs offline and uses the client's CPU power, not the server's.
The Solution
The app logic runs entirely in the Browser.
- The browser downloads your application code (
.dllfiles) and a stripped-down version of the .NET runtime compiled to WebAssembly. - WebAssembly (Wasm) is a binary instruction format that allows non-JS languages (C++, Rust, C#) to run in the browser at near-native speed.
- Once downloaded, the app works offline. It only calls the server for API data.
- Pros: Runs offline, zero server latency for UI interactions, distributes load to client devices.
- Cons: Heavy initial load. The user has to download the .NET runtime (megabytes) before the first page renders.
3. The .NET 8+ Unified Architecture: Blazor Web Apps
The Problem with Pre-.NET 8
Before .NET 8, you had to make a binary choice at the start of your project: "Do I want a Server app or a WebAssembly app?"
- If you chose Server, you couldn't run offline.
- If you chose WebAssembly, your initial load was slow.
The Solution: Blazor Web App (The "Full Stack" UI)
.NET 8 introduced a unified hosting model. You no longer choose the architecture for the whole app; you choose it per component.
This introduces the concept of Interactive Render Modes.
1. Static Server Rendering (SSR) - The Default
By default, Blazor in .NET 8 behaves like traditional web pages. It renders HTML on the server and sends it to the browser. It is fast and SEO-friendly, but not interactive (buttons won't trigger C# code unless you enable a render mode).
2. Interactive Auto (The "Holy Grail")
This is the industry standard for new public-facing apps.
- First Visit: The component renders using Blazor Server. The user sees the page instantly and can interact immediately via the WebSocket.
- Background: The browser quietly downloads the WebAssembly DLLs in the background.
- Subsequent Visits: Once the DLLs are cached, the app switches to WebAssembly.
This solves the "slow startup" of Wasm and the "always connected" requirement of Server.
Analogy: Imagine ordering a pizza.
- Blazor Server: You eat the pizza at the restaurant (fast, but you must be there).
- Blazor Wasm: You order delivery (slow arrival, but you can eat it anywhere).
- Blazor Auto: You start eating at the restaurant, and while you eat, they pack the rest for you to take home automatically.
4. Understanding the Blazor Component Model (Conceptually)
The Problem
HTML is static. Building complex UIs by copying and pasting HTML blocks leads to unmaintainable spaghetti code.
The Solution: Components
In Blazor, everything is a Component. A component is a chunk of UI (HTML) + Logic (C#).
Components are defined in files with the .razor extension.
Anatomy of a .razor file:
@page "/counter"
<!-- 1. The UI (HTML + Razor Syntax) -->
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<!-- @onclick binds the HTML event to the C# method -->
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<!-- 2. The Logic (C# Block) -->
@code {
// Standard C# code here
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}Key Concepts:
- Directives: Top-level commands like
@page(makes the component a route/page) or@inject(Dependency Injection). - Razor Syntax: Using
@transitions from HTML to C#. - Data Binding: Linking a variable to an input field (e.g.,
@bind="userName"). - Nesting: You can use a component inside another just like an HTML tag:
<Counter />.
5. Getting Started: Hands-on Setup
Let's create a .NET 8 Blazor Web App. We will use the Command Line Interface (CLI) as it is the most reliable way to understand what is being generated.
Prerequisites:
- .NET 8.0 SDK or later installed.
- Visual Studio 2022 (17.8+) OR VS Code.
Step 1: Create the Project
Open your terminal/command prompt.
# create a new project named BlazorGuide
# -int Auto: Enables both Server and WebAssembly modes
dotnet new blazor -o BlazorGuide -int AutoStep 2: Navigate and Run
cd BlazorGuide
dotnet watchdotnet watch works like "Hot Reload." It will start the server and watch your files for changes. If you edit a .razor file, the browser will update automatically.
Step 3: Project Structure (What did we just generate?)
Since we selected -int Auto (Interactivity Auto), you will see two projects in your folder. This is a common point of confusion.
BlazorGuide: This is the Server project.
Program.cs: The entry point. Configures the pipeline.Components/App.razor: The root HTML template (contains<html>,<body>).Components/Routes.razor: Handles the routing logic.- Role: Serves the initial HTML and handles API requests.
BlazorGuide.Client: This is the Client (Wasm) project.
- Contains components that need to run in the browser (WebAssembly).
- Role: These components are downloaded to the browser.
Crucial Rule: If a component needs to run in WebAssembly (Auto mode), it must live in the
.Clientproject so it can be compiled into the downloadable DLL.
Interesting Reality Check 🧐
You might notice some "magic" happens when you run the app. In .NET 8, if a component is marked with @rendermode InteractiveAuto, the server will actually pre-render it on the server first (sending plain HTML), and then "hydrate" it with the interactive script.
This means your users see content immediately (milliseconds), even if the heavy logic hasn't finished loading yet. This is a massive improvement over older SPA frameworks where users stared at a white screen or a spinning loader.
Summary Checklist
- Blazor = C# in the browser (plus server-side rendering).
- Server Mode = Logic on server, UI updates via WebSocket (Fast load, needs connection).
- Wasm Mode = Logic in browser, runs on .NET runtime in Wasm (Offline capable, slow start).
- .NET 8+ = Unified model. Use "Auto" mode to get the best of both.
- Components =
.razorfiles combining HTML and C#.
You have successfully unlocked the alphabet of Blazor. In the next guide, we would start forming words (building Layouts and Navigation).
Happy Coding! 👩💻👨💻
References & Further Reading
Challenge
Write a function named processData that accepts an array of objects. Each object in the array represents a user and has the following structure: { "id": number, "name": string, "isActive": boolean, "age": number }.
Your task is to perform the following operations:
- Filter the array to include only the users who are
isActive. - From the filtered list, create a new array containing only the
nameof each user. - Sort the resulting array of names alphabetically.
Finally, return the sorted array of names.
Expected result
The function should return a new array of strings. For example, given the following input array:
const users = [
{ "id": 1, "name": "John", "isActive": true, "age": 32 },
{ "id": 2, "name": "Jane", "isActive": false, "age": 28 },
{ "id": 3, "name": "Peter", "isActive": true, "age": 45 },
{ "id": 4, "name": "Sue", "isActive": true, "age": 22 }
];The expected output would be:
["John", "Peter", "Sue"]