# Blazor Samples Documentation ## Introduction The Blazor Samples repository is the official Microsoft collection of demonstration applications that accompany the ASP.NET Core Blazor documentation. This repository contains over 130 working sample projects organized across multiple .NET versions (3.1, 5.0, 6.0, 7.0, 8.0, 9.0, and 10.0), showcasing best practices and implementation patterns for building modern web applications with Blazor. Each sample is fully functional and designed to demonstrate specific features, from basic component interactions to complex scenarios involving authentication, real-time communication, database integration, and cross-platform hybrid applications. The repository serves as both a learning resource and a reference implementation for developers building Blazor applications. It includes comprehensive examples of Blazor Web Apps (the unified hosting model introduced in .NET 8), Blazor WebAssembly applications running entirely in the browser, and legacy Blazor Server applications. Samples demonstrate integration with Microsoft Entra ID (Azure AD), OpenID Connect authentication, SignalR for real-time features, Entity Framework Core for database operations, .NET MAUI for hybrid mobile apps, and advanced interoperability scenarios with React.js and Web Workers. ## APIs and Key Functions ### Blazor Web App Configuration Configures a modern Blazor Web App with dependency injection, interactive server rendering, and middleware pipeline setup. ```csharp using BlazorSample; using BlazorSample.Components; using static BlazorSample.Components.Pages.ProductDetails; var builder = WebApplication.CreateBuilder(args); // Add Razor Components with interactive server rendering builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); // Register application services builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddHttpClient(); // Add cascading values for component hierarchy builder.Services.AddCascadingValue(sp => new Dalek { Units = 123 }); builder.Services.AddCascadingValue("AlphaGroup", sp => new Dalek { Units = 456 }); builder.Services.AddMemoryCache(); builder.Services.AddTransient(); var app = builder.Build(); // Configure middleware pipeline if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); app.UseHttpsRedirection(); app.UseAntiforgery(); app.MapStaticAssets(); // Map Razor components with interactive server rendering app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run(); ``` ### Blazor WebAssembly Configuration Configures a Blazor WebAssembly application to run entirely in the browser with client-side dependency injection and configuration management. ```csharp using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.Configuration.Memory; using BlazorSample; var builder = WebAssemblyHostBuilder.CreateDefault(args); // Register root components builder.RootComponents.Add("#app"); builder.RootComponents.Add("head::after"); // Configure HttpClient with base address builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); // Register services with appropriate lifetimes builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddCascadingValue(sp => new Dalek { Units = 123 }); builder.Services.AddCascadingValue("AlphaGroup", sp => new Dalek { Units = 456 }); builder.Services.AddTransient(); // Add in-memory configuration var vehicleData = new Dictionary() { { "color", "blue" }, { "type", "car" }, { "wheels:count", "3" }, { "wheels:brand", "Blazin" }, { "wheels:brand:type", "rally" }, { "wheels:year", "2008" }, }; var memoryConfig = new MemoryConfigurationSource { InitialData = vehicleData }; builder.Configuration.Add(memoryConfig); var host = builder.Build(); await host.RunAsync(); ``` ### Entity Framework Core Database Integration Configures Entity Framework Core with DbContextFactory pattern for Blazor applications, including connection string management, migrations, and data seeding. ```csharp using BlazorWebAppMovies.Components; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using BlazorWebAppMovies.Data; var builder = WebApplication.CreateBuilder(args); // Configure DbContext with factory pattern for Blazor builder.Services.AddDbContextFactory(options => options.UseSqlServer( builder.Configuration.GetConnectionString("BlazorWebAppMoviesContext") ?? throw new InvalidOperationException("Connection string 'BlazorWebAppMoviesContext' not found."))); // Add QuickGrid with EF Core adapter builder.Services.AddQuickGridEntityFrameworkAdapter(); // Enable detailed database error pages in development builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); var app = builder.Build(); // Seed database with initial data using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; SeedData.Initialize(services); } if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); app.UseMigrationsEndPoint(); } app.UseHttpsRedirection(); app.UseAntiforgery(); app.MapStaticAssets(); app.MapRazorComponents() .AddInteractiveServerRenderMode(); app.Run(); ``` ### Entity Framework Core DbContext Defines a database context for managing movie entities with Entity Framework Core using primary constructor syntax. ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using BlazorWebAppMovies.Models; namespace BlazorWebAppMovies.Data { public class BlazorWebAppMoviesContext(DbContextOptions options) : DbContext(options) { public DbSet Movie { get; set; } = default!; } } ``` ### Data Model with Validation Defines a strongly-typed data model with comprehensive data annotations for validation and database schema configuration. ```csharp using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BlazorWebAppMovies.Models; public class Movie { public int Id { get; set; } [Required] [StringLength(60, MinimumLength = 3)] public string? Title { get; set; } public DateOnly ReleaseDate { get; set; } [Required] [StringLength(30)] [RegularExpression(@"^[A-Z]+[a-zA-Z()\s-]*$")] public string? Genre { get; set; } [Range(0, 100)] [DataType(DataType.Currency)] [Column(TypeName = "decimal(18, 2)")] public decimal Price { get; set; } [Required] [RegularExpression(@"^(G|PG|PG-13|R|NC-17)$")] public string? Rating { get; set; } } ``` ### Service Layer Implementation Implements a service layer with Entity Framework Core for CRUD operations, following the repository pattern with dependency injection. ```csharp using BlazorApp.Client.Models; using BlazorApp.Client.Services; using BlazorApp.Models; using Microsoft.EntityFrameworkCore; namespace BlazorApp.Services; public class ServerMovieService(MovieContext db) : IMovieService { public async Task GetMoviesAsync(bool watchedMovies) { return watchedMovies ? await db.Movies.Where(t => t.IsWatched).ToArrayAsync() : await db.Movies.ToArrayAsync(); } public async Task PostMovieAsync(Movie movie) { db.Movies.Add(movie); await db.SaveChangesAsync(); } public async Task PutMovieAsync(long id, Movie inputMovie) { var movie = await db.Movies.FindAsync(id); if (movie is null) { return; } movie.Name = inputMovie.Name; movie.IsWatched = inputMovie.IsWatched; await db.SaveChangesAsync(); } public async Task DeleteMovieAsync(long id) { if (await db.Movies.FindAsync(id) is Movie movie) { db.Movies.Remove(movie); await db.SaveChangesAsync(); } } } ``` ### SignalR Hub for Real-Time Communication Creates a SignalR hub for real-time bidirectional communication between server and clients, enabling live chat functionality. ```csharp using Microsoft.AspNetCore.SignalR; namespace BlazorSignalRApp.Hubs; public class ChatHub : Hub { public async Task SendMessage(string user, string message) { await Clients.All.SendAsync("ReceiveMessage", user, message); } } // In Program.cs, register SignalR services: // builder.Services.AddSignalR(); // app.MapHub("/chathub"); // In Razor component, connect to hub: // @inject NavigationManager Navigation // @code { // private HubConnection? hubConnection; // // protected override async Task OnInitializedAsync() // { // hubConnection = new HubConnectionBuilder() // .WithUrl(Navigation.ToAbsoluteUri("/chathub")) // .Build(); // // hubConnection.On("ReceiveMessage", (user, message) => // { // // Handle received message // StateHasChanged(); // }); // // await hubConnection.StartAsync(); // } // } ``` ### Razor Component with Data Binding Creates an interactive Razor component with event handling, data binding, and lifecycle management. ```razor @page "/counter" Counter

Counter

Current count: @currentCount

@code { private int currentCount = 0; private void IncrementCount() => currentCount++; } ``` ### Microsoft Entra ID Authentication Configures comprehensive Microsoft Entra ID (Azure AD) authentication with token acquisition, downstream API calls, and distributed token caching. ```csharp using Azure.Identity; using BlazorWebAppEntra.Client.Weather; using BlazorWebAppEntra.Components; using BlazorWebAppEntra.Weather; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Mvc; using Microsoft.Identity.Web; using Microsoft.Identity.Web.TokenCacheProviders.Distributed; var builder = WebApplication.CreateBuilder(args); // Configure Blazor with authentication state serialization builder.Services.AddRazorComponents() .AddInteractiveServerComponents() .AddInteractiveWebAssemblyComponents() .AddAuthenticationStateSerialization(options => options.SerializeAllClaims = true); // Configure Microsoft Entra ID authentication builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApp(msIdentityOptions => { msIdentityOptions.CallbackPath = "/signin-oidc"; msIdentityOptions.ClientId = "{CLIENT ID (BLAZOR APP)}"; msIdentityOptions.Domain = "{DIRECTORY NAME}.onmicrosoft.com"; msIdentityOptions.Instance = "https://login.microsoftonline.com/"; msIdentityOptions.ResponseType = "code"; msIdentityOptions.TenantId = "{TENANT ID}"; }) .EnableTokenAcquisitionToCallDownstreamApi() .AddDownstreamApi("DownstreamApi", configOptions => { configOptions.BaseUrl = "{BASE URL}"; configOptions.Scopes = [ "{APP ID URI}/Weather.Get" ]; }) .AddDistributedTokenCaches(); // Configure distributed memory cache for token storage builder.Services.AddDistributedMemoryCache(); // Configure token cache with encryption builder.Services.Configure(options => { // Encrypt tokens at rest options.Encrypt = true; }); builder.Services.AddAuthorization(); builder.Services.AddScoped(); var app = builder.Build(); if (app.Environment.IsDevelopment()) { app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error", createScopeForErrors: true); app.UseHsts(); } app.UseHttpsRedirection(); app.UseAntiforgery(); app.MapStaticAssets(); // Map authenticated API endpoint app.MapGet("/weather-forecast", ([FromServices] IWeatherForecaster WeatherForecaster) => { return WeatherForecaster.GetWeatherForecastAsync(); }).RequireAuthorization(); // Map Razor components with multiple render modes app.MapRazorComponents() .AddInteractiveServerRenderMode() .AddInteractiveWebAssemblyRenderMode() .AddAdditionalAssemblies(typeof(BlazorWebAppEntra.Client._Imports).Assembly); // Map authentication endpoints app.MapGroup("/authentication").MapLoginAndLogout(); app.Run(); ``` ### Project Configuration (.csproj) Configures a Blazor Web App project with target framework, nullable reference types, implicit usings, and package references. ```xml net10.0 enable enable true ``` ### Application Configuration (appsettings.json) Configures logging levels, allowed hosts, and custom application URLs for frontend-backend communication. ```json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "BackendUrl": "https://localhost:7212", "FrontendUrl": "https://localhost:7172" } ``` ### Clone Specific Sample with Git Sparse Checkout Downloads a single sample application with minimal git history using sparse checkout for efficient repository access. ```bash # Navigate to desired directory cd ~/documents # Clone with sparse checkout git clone --depth 1 --filter=blob:none https://github.com/dotnet/blazor-samples.git --sparse # Navigate into repository cd blazor-samples # Initialize sparse checkout git sparse-checkout init --cone # Checkout specific sample git sparse-checkout set 9.0/BlazorSample_BlazorWebApp # Alternative: checkout multiple samples git sparse-checkout set 9.0/BlazorSample_BlazorWebApp 9.0/BlazorWebAppMovies ``` ## Summary and Integration Patterns The Blazor Samples repository demonstrates comprehensive implementation patterns for building production-ready web applications across the full spectrum of Blazor hosting models. Primary use cases include learning Blazor fundamentals through working examples, implementing authentication and authorization with enterprise identity providers, building real-time collaborative applications with SignalR, creating data-driven applications with Entity Framework Core, and developing cross-platform hybrid applications with .NET MAUI. The samples serve as reference implementations for the official Microsoft documentation, ensuring developers have working code examples that follow current best practices and architectural patterns. Integration patterns demonstrated throughout the repository include the dependency injection service container for managing application services with appropriate lifetimes (Singleton, Scoped, Transient), the repository pattern for abstracting data access logic, cascading parameters for passing data through component hierarchies, event callbacks for parent-child component communication, and the Backend-for-Frontend (BFF) pattern for securing Blazor WebAssembly applications. The samples showcase modern ASP.NET Core minimal APIs alongside traditional controller-based APIs, demonstrate proper configuration management with appsettings.json and in-memory configuration sources, and illustrate authentication flows with Microsoft Entra ID, OpenID Connect, and ASP.NET Core Identity. Developers can clone the entire repository or use git sparse checkout to download individual samples, run them locally, and adapt the code patterns to their own applications while following the security guidance provided in the accompanying documentation.