# Cheat Sheet

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Project & References
Source: https://www.devtutorials.ai/learn/blazor/project-references/cheat-sheet

> 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

| Command | What it does |
|---|---|
| `dotnet --version` | Shows the installed .NET SDK version |
| `dotnet new blazor -o MyApp` | Creates a Blazor Web App (Interactive Server by default) |
| `dotnet new blazor -o MyApp --interactivity WebAssembly` | Creates an app whose pages run in the browser |
| `dotnet new blazor -o MyApp --interactivity Auto --all-interactive` | Auto render mode, interactive on every page |
| `dotnet new blazor -o MyApp -au Individual` | Adds ASP.NET Core Identity (user accounts) |
| `dotnet new webapi -o MyApi --use-controllers` | Creates a Web API with controllers |
| `dotnet run` | Builds and starts the app |
| `dotnet watch` | Starts the app and reloads it when you save a file |
| `dotnet build` | Compiles the project and shows errors |
| `dotnet add package Name` | Adds a NuGet package |
| `dotnet ef migrations add Name` | Creates an EF Core migration (needs `dotnet tool install --global dotnet-ef`) |
| `dotnet ef database update` | Applies migrations to the database |
| `dotnet user-secrets set "Key" "Value"` | Stores a secret outside the project (development) |
| `dotnet dev-certs https --trust` | Trusts the local HTTPS certificate |

## Razor Syntax

| Syntax | Meaning |
|---|---|
| `@name` | Writes 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`, `else` | Shows markup only when a condition is true |
| `@foreach (var x in list)` | Repeats markup for each item; also `@for`, `@while` |
| `@switch` | Picks one branch by value |
| `@* comment *@` | Razor comment, not sent to the browser |
| `@@` | Writes a real `@` sign |
| `@using`, `@inject`, `@page`, `@attribute`, `@implements` | Directives 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

| Item | Use |
|---|---|
| `.razor` file | One 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 ChildContent` | The 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.css` | CSS that applies to that component only (CSS isolation) |
| `MainLayout.razor`, `@Body`, `@layout` | Shared page frame and where the page goes |
| `<SectionOutlet>`, `<SectionContent>` | Lets a page fill a named spot in the layout |

## Built-in Components

| Component | Use |
|---|---|
| `<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

| Method | When it runs |
|---|---|
| `SetParametersAsync` | First, when parameters arrive (rarely overridden) |
| `OnInitialized` / `OnInitializedAsync` | Once, when the component is created; load data here |
| `OnParametersSet` / `OnParametersSetAsync` | After every parameter change |
| `ShouldRender` | Return `false` to skip a render |
| `OnAfterRender(bool firstRender)` / `OnAfterRenderAsync` | After the HTML is in the page; JS interop is safe here |
| `StateHasChanged()` | Asks the component to render again (timers, events) |
| `Dispose` / `DisposeAsync` | When the component leaves the page; unsubscribe and clean up |

## Forms and Validation

| Item | Use |
|---|---|
| `@bind="value"`, `@bind:event="oninput"` | Two-way binding; update on each key press |
| `@bind-Value` | Binding for input components inside `EditForm` |
| `@onclick`, `@onchange`, `@oninput`, `@onkeydown`, `@onsubmit` | Event handlers |
| `@onclick:preventDefault`, `@onclick:stopPropagation` | Event modifiers |
| `OnValidSubmit`, `OnInvalidSubmit`, `OnSubmit` | What `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 |
| `ValidationAttribute` | Base class for your own rule |
| `EditContext`, `ValidationMessageStore` | Validate in code and add your own messages |
| `FormName` + `[SupplyParameterFromForm]` | Forms on static server-rendered pages |
| `.valid`, `.invalid`, `.modified` | CSS classes Blazor puts on inputs |

## Render Modes

| Mode | Where it runs | Good for |
|---|---|---|
| Static server rendering (no `@rendermode`) | Server, plain HTML, no interactivity | Content pages, login pages |
| `@rendermode InteractiveServer` | Server; UI updates over a SignalR connection | Fast start, data close to the server |
| `@rendermode InteractiveWebAssembly` | Browser (.NET in WebAssembly) | Offline-friendly, less server load |
| `@rendermode InteractiveAuto` | Server first, then WebAssembly once downloaded | Fast first visit and browser later |
| `[StreamRendering]` | Sends the page first, then the data | Slow data on static pages |
| `RendererInfo.IsInteractive`, `RendererInfo.Name` | Tells the component how it is running | Disable 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 app | Account pages that set cookies |

## JS Interop

| Item | Use |
|---|---|
| `@inject IJSRuntime JS` | The 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 `import` | Loads a JavaScript module from `wwwroot` |
| `IJSInProcessRuntime` | Synchronous 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`, `JSDisconnectedException` | Errors from JavaScript, or a closed connection |
| `OnAfterRenderAsync(firstRender)` | The safe place for the first JS call |

## Dependency Injection

| Item | Use |
|---|---|
| `builder.Services.AddScoped<IService, Service>()` | Registers a service in the DI container |
| `AddSingleton` | One object for the whole app |
| `AddScoped` | One object per user connection (Blazor Server) or per request |
| `AddTransient` | A new object every time it is asked for |
| `@inject IService Name` | Gets a service in a `.razor` file |
| `[Inject]` | Gets a service as a property in C# code |
| Constructor parameters | Get services in classes (primary constructors work too) |
| `NavigationManager`, `IJSRuntime`, `HttpClient`, `ILogger<T>` | Common built-in services |

## Services

| Idea | Meaning |
|---|---|
| Service | A 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 service | `FoodService` for menu data, `CartService` for the cart |
| Async methods | Return `Task` or `Task<T>` and are awaited |
| Shared state | A scoped service with an `event Action? OnChange`; components subscribe and unsubscribe |
| Testing | Register a fake implementation of the same interface |

## EF Core

| Item | Use |
|---|---|
| Entity class | A 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`, `AnyAsync` | Read data |
| `Where`, `OrderBy`, `Select`, `Include` | Filter, sort, shape and load related data |
| `Add`, `Update`, `Remove`, then `SaveChangesAsync` | Change data |
| Connection string in `appsettings.json` | Where the database is |
| Migrations (`dotnet ef ...`) or `EnsureCreatedAsync` | Create and update the tables |
| Parameters | EF Core always sends values as parameters, which prevents SQL injection |

## HttpClient

| Item | Use |
|---|---|
| `builder.Services.AddHttpClient<ApiService>(c => c.BaseAddress = ...)` | A typed client for one API |
| `GetFromJsonAsync<T>("api/teas")` | GET and read JSON |
| `PostAsJsonAsync`, `PutAsJsonAsync` | Send JSON |
| `DeleteAsync` | DELETE request |
| `EnsureSuccessStatusCode()` | Throws when the status is not 2xx |
| `HttpRequestException` | Catch it to show a friendly message |
| Status codes | 200 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

| Item | Use |
|---|---|
| Order in `Program.cs` | Middleware 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

| Item | Use |
|---|---|
| Authentication | Finds out who the user is (login) |
| Authorization | Decides what the user may do |
| Cookie scheme | After login, an encrypted cookie proves who the user is |
| `HttpOnly`, `Secure`, `SameSite`, `Expires` | Cookie protection options |
| Claims, `ClaimsIdentity`, `ClaimsPrincipal` | Facts about the user, and the user |
| ASP.NET Core Identity | Users, hashed passwords, roles, lockout, login pages |
| `UserManager.CreateAsync`, `SignInManager.PasswordSignInAsync`, `SignOutAsync` | Register, log in, log out |
| `AuthenticationStateProvider` | The 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`, `RequireRole` | Claims-based policies |
| `IAuthorizationService.AuthorizeAsync` | Check a policy in code |
| `.RequireAuthorization()` | Protect a minimal API endpoint |
| 401 vs 403 | 401: not logged in. 403: logged in, but not allowed |

## Threat Protection

| Threat | Defence |
|---|---|
| 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 |
| Eavesdropping | HTTPS with `UseHttpsRedirection()` and `UseHsts()` |
| Cross-site API calls | CORS with exact origins: `WithOrigins(...)`; never `AllowAnyOrigin()` with logins |
| Secret leaks | Keep keys on the server; WebAssembly code and `wwwroot` are public; User Secrets in development |
| Tampered requests | Validate again on the server (`[ApiController]`, `AddValidation()`); take prices from the database |
| SQL injection | EF Core parameters; never build SQL from user text |
| Open redirects | Only 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.
