Blazor Cheat Sheet

By Syncfusion®, Inc. · Last updated

A short reference of the whole Blazor course: .NET CLI commands, Razor syntax, components and parameters, built-in components, lifecycle methods, forms and validation, render modes, JS interop, dependency injection, services, EF Core, HttpClient, the middleware pipeline, authentication and authorization, and threat protection.

.NET CLI Commands

CommandWhat it does
dotnet --versionShows the installed .NET SDK version
dotnet new blazor -o MyAppCreates a Blazor Web App (Interactive Server by default)
dotnet new blazor -o MyApp --interactivity WebAssemblyCreates an app whose pages run in the browser
dotnet new blazor -o MyApp --interactivity Auto --all-interactiveAuto render mode, interactive on every page
dotnet new blazor -o MyApp -au IndividualAdds ASP.NET Core Identity (user accounts)
dotnet new webapi -o MyApi --use-controllersCreates a Web API with controllers
dotnet runBuilds and starts the app
dotnet watchStarts the app and reloads it when you save a file
dotnet buildCompiles the project and shows errors
dotnet add package NameAdds a NuGet package
dotnet ef migrations add NameCreates an EF Core migration (needs dotnet tool install --global dotnet-ef)
dotnet ef database updateApplies migrations to the database
dotnet user-secrets set "Key" "Value"Stores a secret outside the project (development)
dotnet dev-certs https --trustTrusts the local HTTPS certificate

Razor Syntax

SyntaxMeaning
@nameWrites a C# value into the page (encoded text)
@(price * 2)Explicit expression, for anything with spaces or operators
@code { ... }Fields, properties and methods of the component
@if, else if, elseShows markup only when a condition is true
@foreach (var x in list)Repeats markup for each item; also @for, @while
@switchPicks one branch by value
@* comment *@Razor comment, not sent to the browser
@@Writes a real @ sign
@using, @inject, @page, @attribute, @implementsDirectives at the top of a .razor file
@((MarkupString)html)Renders trusted HTML (never user input)
@key="item.Id"Keeps list items matched when the list changes
@ref="field"Keeps a reference to an element or child component

Components and Parameters

ItemUse
.razor fileOne component; the file name is the component name (PascalCase)
@page "/menu"Makes the component a routable page; {id:int} adds a route parameter
[Parameter]A value the parent passes in, like an HTML attribute
[Parameter, EditorRequired]The parent should always pass it
RenderFragment ChildContentThe markup between the component's tags
EventCallback<T>Lets a child tell its parent that something happened
[CascadingParameter]Receives a value from a <CascadingValue> above it
[SupplyParameterFromQuery]Reads a value from the query string
[SupplyParameterFromForm]Reads posted form data on a static page
Component.razor.cssCSS that applies to that component only (CSS isolation)
MainLayout.razor, @Body, @layoutShared page frame and where the page goes
<SectionOutlet>, <SectionContent>Lets a page fill a named spot in the layout

Built-in Components

ComponentUse
<Router>, <RouteView>Find and show the page for the address
<AuthorizeRouteView>A RouteView that checks [Authorize]
<NavLink>A link that gets the active class on its page
<PageTitle>, <HeadContent>Set the browser tab title and head tags
<EditForm> and <InputText>, <InputNumber>, <InputDate>, <InputSelect>, <InputCheckbox>, <InputTextArea>, <InputRadioGroup>, <InputFile>Forms with two-way binding
<ErrorBoundary>Shows fallback content when a child throws
<Virtualize>Renders only the visible rows of a long list
<CascadingValue>Passes a value to all components below
<AuthorizeView>Shows content by login, role or policy
<AntiforgeryToken>Adds the antiforgery token to a plain HTML form
<DynamicComponent>Renders a component chosen at run time

Lifecycle Methods

MethodWhen it runs
SetParametersAsyncFirst, when parameters arrive (rarely overridden)
OnInitialized / OnInitializedAsyncOnce, when the component is created; load data here
OnParametersSet / OnParametersSetAsyncAfter every parameter change
ShouldRenderReturn false to skip a render
OnAfterRender(bool firstRender) / OnAfterRenderAsyncAfter the HTML is in the page; JS interop is safe here
StateHasChanged()Asks the component to render again (timers, events)
Dispose / DisposeAsyncWhen the component leaves the page; unsubscribe and clean up

Forms and Validation

ItemUse
@bind="value", @bind:event="oninput"Two-way binding; update on each key press
@bind-ValueBinding for input components inside EditForm
@onclick, @onchange, @oninput, @onkeydown, @onsubmitEvent handlers
@onclick:preventDefault, @onclick:stopPropagationEvent modifiers
OnValidSubmit, OnInvalidSubmit, OnSubmitWhat EditForm does on submit
<DataAnnotationsValidator />Checks the model's validation attributes
<ValidationSummary />, <ValidationMessage For="..." />Show all errors, or the errors of one field
[Required], [StringLength], [Range], [EmailAddress], [Phone], [RegularExpression], [Compare]Common validation attributes
ValidationAttributeBase class for your own rule
EditContext, ValidationMessageStoreValidate in code and add your own messages
FormName + [SupplyParameterFromForm]Forms on static server-rendered pages
.valid, .invalid, .modifiedCSS classes Blazor puts on inputs

Render Modes

ModeWhere it runsGood for
Static server rendering (no @rendermode)Server, plain HTML, no interactivityContent pages, login pages
@rendermode InteractiveServerServer; UI updates over a SignalR connectionFast start, data close to the server
@rendermode InteractiveWebAssemblyBrowser (.NET in WebAssembly)Offline-friendly, less server load
@rendermode InteractiveAutoServer first, then WebAssembly once downloadedFast first visit and browser later
[StreamRendering]Sends the page first, then the dataSlow data on static pages
RendererInfo.IsInteractive, RendererInfo.NameTells the component how it is runningDisable buttons until interactive
[PersistentState]Keeps prerendered data for the interactive render (.NET 10)Avoid loading data twice
[ExcludeFromInteractiveRouting]Keeps one page static in an interactive appAccount pages that set cookies

JS Interop

ItemUse
@inject IJSRuntime JSThe service for calling JavaScript
InvokeVoidAsync("fn", args)Calls a JavaScript function with no result
InvokeAsync<T>("fn", args)Calls a JavaScript function and reads its result
IJSObjectReference with importLoads a JavaScript module from wwwroot
IJSInProcessRuntimeSynchronous calls (WebAssembly only)
[JSInvokable]Lets JavaScript call a C# method
DotNet.invokeMethodAsync("Assembly", "Method")JavaScript calls a static C# method
DotNetObjectReference.Create(this)Passes a C# object to JavaScript; dispose it later
JSException, JSDisconnectedExceptionErrors from JavaScript, or a closed connection
OnAfterRenderAsync(firstRender)The safe place for the first JS call

Dependency Injection

ItemUse
builder.Services.AddScoped<IService, Service>()Registers a service in the DI container
AddSingletonOne object for the whole app
AddScopedOne object per user connection (Blazor Server) or per request
AddTransientA new object every time it is asked for
@inject IService NameGets a service in a .razor file
[Inject]Gets a service as a property in C# code
Constructor parametersGet services in classes (primary constructors work too)
NavigationManager, IJSRuntime, HttpClient, ILogger<T>Common built-in services

Services

IdeaMeaning
ServiceA class with the app's logic and data access, outside the UI
Interface (IUserService)Describes what a service can do, so implementations can be swapped
One job per serviceFoodService for menu data, CartService for the cart
Async methodsReturn Task or Task<T> and are awaited
Shared stateA scoped service with an event Action? OnChange; components subscribe and unsubscribe
TestingRegister a fake implementation of the same interface

EF Core

ItemUse
Entity classA C# class that becomes a table; Id is the key
DbContext and DbSet<T>The database session and its tables
AddDbContextFactory<T>(o => o.UseSqlite(...))Registers the database for Blazor Server
await using var db = factory.CreateDbContext()A short-lived context per operation
ToListAsync, FirstOrDefaultAsync, FindAsync, AnyAsyncRead data
Where, OrderBy, Select, IncludeFilter, sort, shape and load related data
Add, Update, Remove, then SaveChangesAsyncChange data
Connection string in appsettings.jsonWhere the database is
Migrations (dotnet ef ...) or EnsureCreatedAsyncCreate and update the tables
ParametersEF Core always sends values as parameters, which prevents SQL injection

HttpClient

ItemUse
builder.Services.AddHttpClient<ApiService>(c => c.BaseAddress = ...)A typed client for one API
GetFromJsonAsync<T>("api/teas")GET and read JSON
PostAsJsonAsync, PutAsJsonAsyncSend JSON
DeleteAsyncDELETE request
EnsureSuccessStatusCode()Throws when the status is not 2xx
HttpRequestExceptionCatch it to show a friendly message
Status codes200 OK, 201 Created, 204 No Content, 400 Bad Request, 401, 403, 404, 500
[ApiController], [Route("api/[controller]")], [HttpGet("{id}")]Build the API side with controllers

Middleware Pipeline

ItemUse
Order in Program.csMiddleware run in the order added, and in reverse on the way out
app.Use(async (context, next) => ...)Inline middleware; call await next() to pass on
app.Run(...)The last step; it always answers
app.Map("/path", ...)A branch for paths that start with /path
Not calling next()Short-circuits the pipeline
app.UseMiddleware<T>()A middleware class with InvokeAsync(HttpContext)
UseExceptionHandler("/Error")Friendly error page (outside Development)
UseStatusCodePagesWithReExecute("/not-found")A page for 404 and other errors
UseHttpsRedirection(), UseHsts()HTTPS only
UseAntiforgery()Checks antiforgery tokens on form posts
MapStaticAssets(), MapRazorComponents<App>(), MapControllers()Static files, Blazor pages, API controllers

Authentication & Authorization

ItemUse
AuthenticationFinds out who the user is (login)
AuthorizationDecides what the user may do
Cookie schemeAfter login, an encrypted cookie proves who the user is
HttpOnly, Secure, SameSite, ExpiresCookie protection options
Claims, ClaimsIdentity, ClaimsPrincipalFacts about the user, and the user
ASP.NET Core IdentityUsers, hashed passwords, roles, lockout, login pages
UserManager.CreateAsync, SignInManager.PasswordSignInAsync, SignOutAsyncRegister, log in, log out
AuthenticationStateProviderThe service that knows the current user
AddCascadingAuthenticationState() and [CascadingParameter] Task<AuthenticationState>The user in every component
@attribute [Authorize], [Authorize(Roles = "Admin")], [Authorize(Policy = "Name")]Protect pages and API actions
[AllowAnonymous]Opens one action inside a protected controller
<AuthorizeView> with <Authorized> and <NotAuthorized>Show content by login, role or policy
AddAuthorization(o => o.AddPolicy(...)), RequireClaim, RequireRoleClaims-based policies
IAuthorizationService.AuthorizeAsyncCheck a policy in code
.RequireAuthorization()Protect a minimal API endpoint
401 vs 403401: not logged in. 403: logged in, but not allowed

Threat Protection

ThreatDefence
XSS (injected scripts)Write user text with @text; never cast user input to MarkupString; sanitize rich HTML
CSRF (forged form posts)Antiforgery tokens: UseAntiforgery(), <EditForm>, <AntiforgeryToken />; SameSite cookies
EavesdroppingHTTPS with UseHttpsRedirection() and UseHsts()
Cross-site API callsCORS with exact origins: WithOrigins(...); never AllowAnyOrigin() with logins
Secret leaksKeep keys on the server; WebAssembly code and wwwroot are public; User Secrets in development
Tampered requestsValidate again on the server ([ApiController], AddValidation()); take prices from the database
SQL injectionEF Core parameters; never build SQL from user text
Open redirectsOnly follow return addresses on your own site

What to Remember

  • This page is a reminder, not a replacement for the lessons. Each table follows a lesson of the course, so go back to that lesson when you need the full explanation and examples.
  • Most Blazor work is the same few steps: a component with a route, data from a service through @inject, a form with validation, and [Authorize] where only some users may go.
  • Security is not one feature: encode output, keep antiforgery tokens on, use HTTPS, keep secrets on the server and validate on the server.
  • When in doubt, check the official ASP.NET Core Blazor docs at learn.microsoft.com.

Next: You have finished the course. Run the Tea Shop project from the capstone on your own computer, then add a feature of your own.