Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 41 ยท Hosting Models and Deployment

Publishing and Deploying Blazor Apps

Publish a Blazor app for production, choose between server hosting, containers and static hosting, trim and compress WebAssembly downloads, configure the environment and check health.

Running dotnet run on your laptop is development. Deployment means producing an optimized build, putting it on a machine users can reach, giving it the right configuration and making sure it keeps running. What you deploy depends on the render modes you chose in Blazor Hosting Models and Render Modes: an app with server rendering needs a server that runs ASP.NET Core, while a standalone WebAssembly app is just static files.

The commands and config below are real, but this tutorial's runner cannot build or host a website, so they are read-only. The runnable examples are stand-ins that model decisions such as bundle size and environment settings.

Publishing

dotnet publish compiles in Release mode, trims what it can, and writes everything needed to a folder:

Terminal
dotnet publish -c Release -o ./publish

What lands in publish depends on the project:

Project type Output Needs to run
Blazor Web App (server) MyApp.dll, wwwroot, config ASP.NET Core runtime (or self-contained)
Web App with WebAssembly parts the above plus a _framework folder with .wasm and assemblies same server
Standalone WebAssembly only static files in wwwroot any static file host

Use -r linux-x64 --self-contained when the target machine has no .NET installed, and --no-self-contained (the default) to rely on the shared runtime and keep the package small.

Configuration per environment

ASP.NET Core selects settings with the ASPNETCORE_ENVIRONMENT variable: Development, Staging or Production. Files layer on top of each other:

JSON
// appsettings.json (all environments)
{
  "ConnectionStrings": { "Default": "Data Source=app.db" },
  "Logging": { "LogLevel": { "Default": "Information" } }
}

// appsettings.Production.json
{
  "Logging": { "LogLevel": { "Default": "Warning" } }
}

Environment variables override files, which is how secrets reach a container (ConnectionStrings__Default with double underscores for nesting). Never commit production secrets to the repository.

C# Stand-in: layered configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Later sources win: environment variables beat appsettings.Production.json, which beats appsettings.json. This is the rule to remember when a setting "does not take effect".

Hosting a server-rendered Blazor app

A server app is a normal ASP.NET Core app. Common targets:

  • A Linux VM running the app with Kestrel behind a reverse proxy such as nginx or Caddy that handles HTTPS. Run it as a systemd service so it restarts on failure.
  • IIS on Windows with the ASP.NET Core Hosting Bundle.
  • A PaaS such as Azure App Service, which handles the proxy and scaling for you.
  • A container, covered next.

Interactive Server needs WebSockets (or falls back to long polling) to the app, so proxies must allow upgrade headers. With several server instances, a circuit lives on one instance, so use sticky sessions (session affinity) so a user's connection always reaches the same one. Check this when "it works on one server but disconnects behind the load balancer".

NGINX
location / {
    proxy_pass         http://127.0.0.1:5000;
    proxy_http_version 1.1;
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    proxy_set_header   Host $host;
    proxy_read_timeout 100s;
}

If the app sits behind a proxy, also enable forwarded headers (app.UseForwardedHeaders()), so the app sees the real scheme (https) and client IP.

Containers

A multi-stage Dockerfile keeps the image small by building with the SDK and running on the lighter runtime image:

DOCKERFILE
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY --from=build /app .
ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080
ENTRYPOINT ["dotnet", "MyApp.dll"]

Pass secrets at run time (docker run -e ConnectionStrings__Default=...) rather than baking them into the image.

Hosting standalone WebAssembly

A standalone WebAssembly app has no server code, so any static host works: GitHub Pages, Azure Static Web Apps, Netlify, an S3 bucket plus CDN, or nginx. Two things need attention:

  1. Client-side routing. Visiting /products/42 directly asks the host for a file that does not exist. Configure a fallback that serves index.html for unknown paths.
  2. Base path. If the site lives in a sub-folder (GitHub Pages project sites), set <base href="/my-repo/" /> in index.html.
NGINX
location / {
    try_files $uri $uri/ /index.html;
}

Making the download smaller

The first load of a WebAssembly app is its biggest cost. Publishing already helps:

  • Trimming removes unused framework code (on by default in Release publish).
  • Compression: Brotli compressed files are produced and typically cut the download by around two thirds when the host serves them with Content-Encoding: br.
  • Lazy loading assemblies: rarely used areas (an admin screen, a PDF library) can be fetched only when visited.
  • AOT compilation (<RunAOTCompilation>true</RunAOTCompilation>) makes CPU-heavy code faster but increases the download size and build time, so it is a speed-versus-size trade.
  • Cache hashed files long-term, since their names change with their content.

This stand-in applies estimated savings so you can reason about the trade-offs. The percentages are rough assumptions for illustration, not measurements of any real app.

C# Stand-in: estimating the WebAssembly download

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Health checks and logging

Production apps should expose a health endpoint so the load balancer or orchestrator can tell whether the app is alive:

C#
builder.Services.AddHealthChecks();
app.MapHealthChecks("/healthz");

Log to stdout in containers (the platform collects it) and keep the default log level at Warning or Information in production. Turn on detailed circuit errors only in development, because they expose internals:

C#
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents(o => o.DetailedErrors = builder.Environment.IsDevelopment());

Deployment checklist

  • Build in Release, run the tests first.
  • Set ASPNETCORE_ENVIRONMENT=Production; keep secrets in environment variables or a secret store.
  • Serve everything over HTTPS and enable HSTS.
  • Allow WebSockets through proxies; use sticky sessions with several instances (Interactive Server).
  • Add the index.html fallback for standalone WebAssembly.
  • Add a health check and watch logs after the first deploy.
  • Plan rollbacks: keep the previous build or image tag.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Blazor app can be hosted on a plain static file host?

    A standalone WebAssembly app publishes only static files; the others need an ASP.NET Core server.
  2. 2. Which source wins when a setting exists in appsettings.json, appsettings.Production.json and an environment variable?

    Later configuration sources override earlier ones, and environment variables come last.
  3. 3. Why do several instances of an Interactive Server app need sticky sessions?

    The circuit holds component state in server memory on a specific instance.
  4. 4. What does a fallback to index.html do for standalone WebAssembly?

    The host would otherwise return 404 for paths that exist only in the client-side router.

Summary

  • dotnet publish -c Release produces the deployable output; the project type decides what must host it.
  • Configuration layers: appsettings.json, environment file, then environment variables (highest priority).
  • Server-rendered apps need ASP.NET Core, WebSocket-friendly proxies and sticky sessions when scaled out.
  • Standalone WebAssembly is static files plus an index.html fallback and the right base path.
  • Trim, compress and lazy-load to shrink downloads; AOT trades size for speed.
  • Add HTTPS, health checks, production logging and a rollback plan.

Next: Project: Task Board