skip to content

Blazor

Blazor builds web UI from C# Razor components that run on the server, on WebAssembly in the browser, or both in one Blazor Web App. Interviewers probe render modes and where state lives.

on this pageshow

explore

questions

page 1 of 2

In Blazor, how does AuthorizeView decide what to render, and what do its Roles, Policy and NotAuthorized parameters do?

level: juniorimportance: must knowfreq 60%

answer

  1. needs a cascading Task<AuthenticationState>
  2. no Roles or Policy: default policy
  3. Roles is a comma list, any one
  4. Roles plus Policy: both must pass
  5. hides markup, secures nothing

basics

~20 s

AuthorizeView awaits the cascading authentication state and runs the user through IAuthorizationService. It renders its child content when authorized and NotAuthorized otherwise; Roles accepts any listed role, Policy names a registered policy, and with neither it just requires a signed-in user.

solid answer

~40 s

`AuthorizeView` reads the cascading `Task<AuthenticationState>` (supplied by `AddCascadingAuthenticationState()`), then calls `IAuthorizationService.AuthorizeAsync` with a policy built from its parameters. With no `Roles` or `Policy` it uses the default policy, which only requires an authenticated user. `Roles="Captain, Coach"` passes if the user has any one of them; `Policy="ActiveMembership"` names a policy registered with `AddAuthorization`; if both are set, both must pass. Content goes in the child content or `<Authorized>` (not both), the fallback in `<NotAuthorized>`, and `<Authorizing>` shows while the state task is pending. Both fragments receive `context`, an `AuthenticationState`, so `@context.User` is available. It only decides what markup renders: the page and the handlers behind a hidden button still need their own checks.

code

razor · 10 lines
razor
<AuthorizeView Roles="Captain">
    <p>Captain tools for @context.User.Identity?.Name</p>
    <AuthorizeView Policy="ActiveMembership" Context="membership">
        <button @onclick="OpenRegattaEntries">Enter regatta</button>
    </AuthorizeView>
</AuthorizeView>

@code {
    private void OpenRegattaEntries() { /* the service re-checks the user */ }
}

go deeper

for a junior

Recall the Authorized and NotAuthorized fragments, the context variable, that Roles means any listed role, and that no Roles or Policy means signed-in users only.

for a middle

Explain the cascading Task<AuthenticationState>, the IAuthorizationService call, how Roles and Policy combine, and why setting both ChildContent and Authorized throws.

for a senior

Show you treat AuthorizeView as presentation only and put enforcement on pages, services and web APIs, especially when components run in WebAssembly.

for a principal

Discuss how a team keeps UI visibility rules and server policies from drifting apart, for example by naming every check as a shared policy.

## What `AuthorizeView` is `AuthorizeView` is a built-in component in `Microsoft.AspNetCore.Components.Authorization`. It shows one piece of UI to users who pass an authorization check and, optionally, another piece to users who do not. A rowing-club membership portal uses it to show the **Crew roster** and **Boat bookings** menu items only to captains and coaches, and a **Join the club** link to everyone else. ```razor <AuthorizeView Roles="Captain, Coach"> <Authorized> <NavLink href="admin/crews">Crew roster</NavLink> <NavLink href="admin/boats">Boat bookings</NavLink> </Authorized> <NotAuthorized> <NavLink href="join">Join the club</NavLink> </NotAuthorized> </AuthorizeView> ``` ## How it decides Every time its parameters are set, the component: 1. reads a cascading parameter of type `Task<AuthenticationState>`; if none is cascaded it throws an `InvalidOperationException` ("Authorization requires a cascading parameter of type Task<AuthenticationState>..."); 2. shows the `Authorizing` content while it awaits that task; 3. builds a policy from `Roles` and `Policy` and calls `IAuthorizationService.AuthorizeAsync(user, Resource, policy)`, the same authorization engine the server uses for endpoints; 4. renders the authorized content or `NotAuthorized`. The cascading value usually comes from `builder.Services.AddCascadingAuthenticationState()` in `Program.cs`, which the Blazor Web App template calls when authentication is enabled. ## Its parameters | Parameter | Meaning | |---|---| | `ChildContent` or `Authorized` | content for authorized users; the two are synonyms and setting both throws | | `NotAuthorized` | content for everyone else | | `Authorizing` | content while the authentication state task is still running | | `Roles` | comma-separated role names; one matching role is enough | | `Policy` | the name of one registered authorization policy | | `Resource` | an object passed to `AuthorizeAsync` for resource-based checks | Rules worth knowing: - **Neither `Roles` nor `Policy`:** the **default policy** applies, which by default authorizes any signed-in user and rejects anonymous ones. - **Both `Roles` and `Policy`:** the user must satisfy both. - **All of several roles:** nest one `AuthorizeView` inside another and give the inner one a different `Context` name to avoid a clash with the outer `context`. - **Role names** are compared as ordinary strings, typically case-sensitive; policy names are looked up case-insensitively. - **`context`** is the `AuthenticationState`, so `@context.User.Identity?.Name` greets the member. Defining what a policy such as `ActiveMembership` requires belongs to the server's authorization setup; `AuthorizeView` only refers to it by name. ## Why it is UI only `AuthorizeView` changes the rendered output. It does not protect anything the markup points to: - **A hidden `NavLink`** does not stop a member typing `/admin/boats` into the address bar. The page itself needs `@attribute [Authorize(Roles = "Captain")]`. - **A hidden button** does not protect its handler. Code elsewhere can call the same method, so the service that cancels a boat booking checks the user too. - **With WebAssembly interactivity** the component code runs in the browser and can be modified by the user. Content and actions that matter must come from a web API that authorizes every request on the server. - **With Interactive Server** the handler runs on the server, but the same rule holds: authorize in the operation, not only in the markup. ## Where it works `AuthorizeView` works in every render mode. Under static server-side rendering it evaluates once per request, so the menu above is correct in the HTML the server sends. When interactive, the component re-evaluates whenever the cascading authentication state changes, for example after a revalidating provider signs the user out. `Authorizing` content is rarely visible in server-side rendering because the state is known immediately; it matters when a client-side provider has to fetch the user asynchronously. ## Mistakes that come up - **Setting both `ChildContent` and `<Authorized>`.** Markup placed directly inside the component is `ChildContent`; adding an `<Authorized>` element as well throws an `InvalidOperationException` ("Do not specify both 'Authorized' and 'ChildContent'"). - **Nesting without renaming `context`.** Two nested `AuthorizeView` components both expose `context`; give the inner one `Context="inner"` to avoid the name collision. - **Role spelling.** `Roles="captain"` does not match a `Captain` role claim when the comparison is case-sensitive, which is the usual case. - **A policy registered only on the server.** Components running in WebAssembly evaluate with the browser's own authorization services (`AddAuthorizationCore()` in the `.Client` project), so a `Policy` name missing there throws an `InvalidOperationException` ("The AuthorizationPolicy named: '...' was not found."). ## Interview summary Say what it renders, how roles and policies combine, where the state comes from, and, unprompted, that it is a display tool and not an access-control boundary.

  • How do you require both the Captain and Coach roles with AuthorizeView?
    `Roles="Captain, Coach"` accepts either role. To require both, nest `<AuthorizeView Roles="Coach" Context="inner">` inside `<AuthorizeView Roles="Captain">`, or define a policy that requires both roles and pass its name to `Policy`.
  • The admin menu items are hidden for ordinary members. Is the admin page protected?
    No. `AuthorizeView` only removes markup. A member can still type the URL, so the routable page needs `@attribute [Authorize(Roles = "Captain")]`, and the services or web APIs it calls must authorize the operation on the server.
  • What does the Authorizing fragment show in a server-rendered Blazor Web App?
    Usually nothing visible: the server knows the user as soon as the request or circuit starts, so the state task completes at once. `Authorizing` matters when a client-side `AuthenticationStateProvider` fetches the user asynchronously.

  • Roles="Captain, Coach" requires the user to hold both roles
  • Without Roles or Policy, AuthorizeView shows its content to anonymous users
  • Hiding a button with AuthorizeView prevents its handler from being called
  • AuthorizeView reads HttpContext.User directly, so it needs no cascading state
  • Removing a NavLink with AuthorizeView protects the page it links to
open as a page

In a Blazor component, how do [Parameter] and [EditorRequired] declare inputs, and why shouldn't the component assign its own parameter property?

level: juniorimportance: must knowfreq 70%

basics

~20 s

A parameter is a public auto property marked [Parameter]; adding [EditorRequired] makes the editor and build warn when a caller omits it, but nothing enforces it at runtime. A component should not assign its own parameter, because a later parent render can pass its value again and overwrite the change.

open as a page

In a Blazor Web App, how do EditForm, DataAnnotationsValidator, ValidationMessage and ValidationSummary work together to validate a form?

level: juniorimportance: must knowfreq 72%

basics

~20 s

EditForm builds an EditContext for its Model and cascades it. DataAnnotationsValidator subscribes to it and runs the model's attributes on each field change and on submit; ValidationMessage shows one field's errors and ValidationSummary lists them all.

open as a page

In a Blazor component, how do you call a JavaScript function through IJSRuntime, and when do you use InvokeAsync<TValue> rather than InvokeVoidAsync?

level: juniorimportance: must knowfreq 66%

basics

~10 s

Inject IJSRuntime and call InvokeAsync<TValue>("identifier", args) when you need the result, or InvokeVoidAsync when you do not. The identifier is resolved from window, arguments and results are JSON-serialized, and a returned Promise is awaited.

open as a page

In a Blazor component, in what order do SetParametersAsync, OnInitialized(Async), OnParametersSet(Async) and OnAfterRender(Async) run, and which run again later?

level: juniorimportance: must knowfreq 72%

basics

~10 s

On first use: SetParametersAsync assigns parameters, then OnInitialized, OnInitializedAsync, OnParametersSet and OnParametersSetAsync run, the component renders, and OnAfterRender(Async) runs with firstRender true. Later parameter updates repeat only SetParametersAsync, OnParametersSet(Async), render and OnAfterRender.

open as a page

In a Blazor Web App, how does an @page directive make a component routable, and how do route parameters and constraints reach it?

level: juniorimportance: must knowfreq 62%

basics

~20 s

The Razor compiler turns @page into a [Route] attribute that Blazor's routing reads. A {Name} segment fills the [Parameter] property of that name, and a typed constraint such as {Id:int} filters the match and converts the value.

open as a page

In a Blazor Web App, where does a component's in-memory state live on Interactive Server and on WebAssembly, and what survives a browser refresh?

level: juniorimportance: must knowfreq 62%

basics

~20 s

On Interactive Server, component fields and circuit-scoped services live in server memory inside the user's circuit; on WebAssembly they live in the browser tab's .NET runtime. A full refresh starts a new circuit or app, so only data saved elsewhere survives.

open as a page

In a Blazor Web App, what does @attribute [Authorize] on a page enforce, and when does AuthorizeRouteView's NotAuthorized content actually render?

level: middleimportance: must knowfreq 52%

basics

~20 s

[Authorize] on a routable page is enforced twice: by the authorization middleware when the page is requested from the server, and by AuthorizeRouteView during interactive routing. NotAuthorized renders only in the second case; server requests get a challenge or forbid instead.

open as a page

In Blazor, why should a reusable data grid expose its sort request as an EventCallback<T> parameter rather than an Action<T>?

level: middleimportance: must knowfreq 60%

basics

~20 s

An EventCallback<T> remembers the component that created it, so invoking it runs the parent's handler and then re-renders the parent, including after an async handler completes. An Action<T> just calls the method, so the parent's UI stays stale until something else renders it.

open as a page

In a Blazor EditForm, when do you pass an EditContext instead of a Model, and what changes when you handle OnSubmit yourself?

level: middleimportance: must knowfreq 58%

basics

~10 s

Pass Model when EditForm may build the EditContext itself; pass your own EditContext when code needs it: custom message stores, modified-field checks or field-change events. OnSubmit replaces OnValidSubmit/OnInvalidSubmit, so you call Validate() yourself.

open as a page

In a prerendered Blazor Web App component, why does an IJSRuntime call in OnInitializedAsync throw, and where should a trail map's first JavaScript call go?

level: middleimportance: must knowfreq 60%

basics

~20 s

During prerendering the component runs on the server to produce HTML before any browser connection exists, so JS interop throws an InvalidOperationException. Put the first call in OnAfterRenderAsync guarded by firstRender, which runs only once the component is interactive and its elements exist.

open as a page

In a .NET 10 Blazor Web App, what are the four render modes, where does each run a component's code, and what does each cost?

level: middleimportance: must knowfreq 74%

basics

~20 s

A Blazor Web App renders each component as static SSR (server HTML, no interactivity), Interactive Server (events handled on the server over a SignalR circuit), Interactive WebAssembly (the .NET runtime runs in the browser) or Interactive Auto (Server first, WebAssembly once the bundle is cached).

open as a page

In a Blazor Web App, what does prerendering do to an interactive component, what problems follow, and how do you detect or disable it?

level: middleimportance: must knowfreq 62%

basics

~20 s

Prerendering renders an interactive component to HTML on the server first, so content appears before interactivity starts. The component is then created again when it becomes interactive, which doubles initialization and breaks client-only services; detect it with RendererInfo, disable it with prerender: false.

open as a page

In Blazor, what does NavigationManager.NavigateTo do with forceLoad false versus true, and when must you force a full page load?

level: middleimportance: must knowfreq 55%

basics

~20 s

With forceLoad false, the default, NavigateTo stays inside Blazor: the interactive router swaps components or enhanced navigation patches the page. forceLoad true loads a new document, which non-Blazor endpoints and a fresh app state need.

open as a page

In a Blazor Web App, what does AddScoped mean on Interactive Server and on WebAssembly, and how do you build a shared cake-basket state container safely?

level: middleimportance: must knowfreq 64%

basics

~20 s

On Interactive Server a scoped service lives as long as the user's circuit; in WebAssembly there are no DI scopes, so scoped acts like a singleton for that tab. Register the basket as scoped, raise an event on change, and have components subscribe and unsubscribe.

open as a page

Why does injecting a DbContext directly into Blazor Interactive Server components fail under concurrent use, and how does IDbContextFactory fix it?

level: seniorimportance: must knowfreq 52%

basics

~10 s

AddDbContext registers a scoped DbContext, and on Interactive Server a scope is the whole circuit, so every component shares one non-thread-safe context. Inject IDbContextFactory<TContext> instead and create a short-lived context per operation with CreateDbContextAsync.

open as a page

In a Blazor Web App, why does a button's @onclick never run on a page without @rendermode, and what fixes it?

level: juniorimportance: should knowfreq 58%

basics

~20 s

Without a render mode the page is static SSR: the server sends finished HTML and discards the component, so nothing is left to run the handler. Give the page an interactive render mode, and make sure Program.cs registers that mode's services and endpoints.

open as a page

In a Blazor component, how should code read the current user: a cascading Task<AuthenticationState>, AuthenticationStateProvider, or HttpContext, and what does AddCascadingAuthenticationState register?

level: middleimportance: should knowfreq 45%

basics

~10 s

Use a [CascadingParameter] Task<AuthenticationState>; AddCascadingAuthenticationState registers it as a root-level cascading value fed by AuthenticationStateProvider and refreshed on its changes. Inject the provider only in services, and use HttpContext only during static SSR.

open as a page

In Blazor, what must a custom component declare so a parent can use @bind-Value on it, and how do @bind-Value:after and :get/:set change that?

level: middleimportance: should knowfreq 50%

basics

~20 s

The component needs a [Parameter] Value and a matching [Parameter] EventCallback<T> ValueChanged; @bind-Value then expands to both. The child reports a new value by invoking ValueChanged, never by assigning Value; :after adds a follow-up step and :get/:set take over the assignment.

open as a page

In a Blazor data grid component, how do @typeparam and RenderFragment<TItem> parameters let callers template each row, and what is the context variable?

level: middleimportance: should knowfreq 45%

basics

~20 s

A grid declares @typeparam TItem and a [Parameter] RenderFragment<TItem> RowTemplate; it calls @RowTemplate(item) for each row. Callers write the template as a child element, and inside it the current item is available as context, or under a name set with the Context attribute.

open as a page

In Blazor, what do built-in input components such as InputText, InputNumber and InputDate add over a plain input element bound with @bind?

level: middleimportance: should knowfreq 45%

basics

~20 s

The Input components derive from InputBase<TValue> and join the cascaded EditContext: each change notifies it so validation runs, unparsable text becomes a validation message, and they render validity CSS classes, aria-invalid and a form-field name a plain input lacks.

open as a page

In Blazor, how does the InputFile component hand selected files to your code, and which default limits do IBrowserFile and InputFileChangeEventArgs enforce?

level: middleimportance: should knowfreq 40%

basics

~10 s

InputFile raises OnChange with an InputFileChangeEventArgs; you read IBrowserFile objects from File or GetMultipleFiles and stream each through OpenReadStream. Defaults: 10 files, then GetMultipleFiles throws; 500 KB (512,000 bytes) per stream, then an IOException.

open as a page

When a JavaScript map in a Blazor component must call back into .NET on a marker click, how do DotNetObjectReference and [JSInvokable] work?

level: middleimportance: should knowfreq 48%

basics

~10 s

Wrap the component with DotNetObjectReference.Create(this), pass it to JavaScript, and mark the target public method [JSInvokable]. JavaScript calls dotNetHelper.invokeMethodAsync('OnTrailSelected', id); dispose the reference when the component goes away.

open as a page

In an Interactive Server Blazor component, why does calling StateHasChanged from a System.Threading.Timer callback throw, and how does InvokeAsync fix it?

level: middleimportance: should knowfreq 46%

basics

~20 s

Rendering must happen on the renderer's Dispatcher, and a Timer callback runs on a thread-pool thread, so StateHasChanged throws an InvalidOperationException saying the thread is not associated with the Dispatcher. Wrapping the call in InvokeAsync runs it on the Dispatcher.

open as a page

In a Blazor weather widget, why does chart setup belong in OnAfterRenderAsync guarded by firstRender, and what happens if that method calls StateHasChanged unconditionally?

level: middleimportance: should knowfreq 52%

basics

~20 s

OnAfterRenderAsync runs only after an interactive render has reached the UI, so the chart's element exists; firstRender limits one-time setup to the first call. Calling StateHasChanged there without a guard triggers another render and another OnAfterRenderAsync, an endless render loop.

open as a page

In a Blazor Web App, what does [StreamRendering] change when a statically rendered page awaits slow data in OnInitializedAsync?

level: middleimportance: should knowfreq 34%

basics

~20 s

Without it the server waits for the page's async work before sending any HTML. With [StreamRendering] it sends the first render (for example a loading message) at once, then streams the finished markup later in the same response, which blazor.web.js patches into place.

open as a page

In a Blazor Web App, how does [SupplyParameterFromQuery] bind catalog filters from the query string, and how should a page update those filters?

level: middleimportance: should knowfreq 44%

basics

~20 s

[SupplyParameterFromQuery] fills a property from the query string key of the same name, or from Name. To change a filter, build the URL with NavigationManager.GetUriWithQueryParameter(s) and call NavigateTo; the same page instance receives new values and OnParametersSet runs.

open as a page

In Blazor Interactive Server, how do ProtectedLocalStorage and ProtectedSessionStorage keep a cake basket in the browser, and what are their limits?

level: middleimportance: should knowfreq 36%

basics

~20 s

They wrap the browser's localStorage and sessionStorage: SetAsync serializes the value and encrypts it with ASP.NET Core Data Protection, GetAsync decrypts it into a ProtectedBrowserStorageResult<T>. They need JS interop, so they fail during prerendering, and they work only in server-side Blazor.

open as a page

In an Interactive Server Blazor app, why can a member whose Captain role was revoked keep seeing admin UI, and how does RevalidatingServerAuthenticationStateProvider address it?

level: seniorimportance: should knowfreq 34%

basics

~20 s

A circuit keeps the user from the connection that started it, and in-circuit navigation sends no cookies, so a revoked role lingers. RevalidatingServerAuthenticationStateProvider re-checks the user every RevalidationInterval and swaps in an anonymous user when validation fails.

open as a page

showing 1–30 of 46