ASP.NET Core Blazor static files
Note
This isn't the latest version of this article. For the current release, see the .NET 8 version of this article.
Warning
This version of ASP.NET Core is no longer supported. For more information, see .NET and .NET Core Support Policy. For the current release, see the .NET 8 version of this article.
Important
This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
For the current release, see the .NET 8 version of this article.
This article describes Blazor app configuration for serving static files.
Static asset middleware
This section applies to server-side Blazor apps.
Serving static assets is managed by either of the two middlewares described in the following table.
Middleware | API | .NET Version | Description |
---|---|---|---|
Map Static Assets | MapStaticAssets |
.NET 9 or later | Optimizes the delivery of static assets to clients. |
Static Files | UseStaticFiles | All .NET versions | Serves static assets to clients without the optimizations of MapStaticAssets but useful for some tasks that MapStaticAssets isn't capable of managing. |
Configure Map Static Assets Middleware by calling MapStaticAssets
in the app's request processing pipeline, which performs the following:
- Sets the ETag and Last-Modified headers.
- Sets caching headers.
- Uses Caching Middleware.
- When possible, serves compressed static assets.
- Works with a Content Delivery Network (CDN) (for example, Azure CDN) to serve the app's static assets closer to the user.
- Minifies the app's static assets.
MapStaticAssets
operates by combining build and publish processes to collect information about the static assets in the app. This information is utilized by the runtime library to efficiently serve the static assets to browsers.
MapStaticAssets
can replace UseStaticFiles in most situations. However, MapStaticAssets
is optimized for serving the assets from known locations in the app at build and publish time. If the app serves assets from other locations, such as disk or embedded resources, UseStaticFiles should be used.
MapStaticAssets
provides the following benefits not found with UseStaticFiles:
- Build-time compression for all the assets in the app: Gzip (
Content-Encoding: gz
) during development and Gzip with Brotli (Content-Encoding: br
) during publish. - Content based
ETags
are generated for each static asset, which are Base64-encoded strings of the SHA-256 hashes of the static assets. This ensures that the browser only redownloads a file if its contents have changed.
Static File Middleware (UseStaticFiles) is useful in the following situations that MapStaticAssets
can't handle:
- Applying a path prefix to Blazor WebAssembly static asset files, which is covered in the Prefix for Blazor WebAssembly assets section.
- Configuring file mappings of extensions to specific content types and setting static file options, which is covered in the File mappings and static file options section.
Configure Static File Middleware to serve static assets to clients by calling UseStaticFiles in the app's request processing pipeline. For more information, see Static files in ASP.NET Core.
In releases prior to .NET 8, Blazor framework static files, such as the Blazor script, are served via Static File Middleware. In .NET 8 or later, Blazor framework static files are mapped using endpoint routing, and Static File Middleware is no longer used.
Static Web Asset Project Mode
This section applies to the .Client
project of a Blazor Web App.
The required <StaticWebAssetProjectMode>Default</StaticWebAssetProjectMode>
setting in the .Client
project of a Blazor Web App reverts Blazor WebAssembly static asset behaviors back to the defaults, so that the project behaves as part of the hosted project. The Blazor WebAssembly SDK (Microsoft.NET.Sdk.BlazorWebAssembly
) configures static web assets in a specific way to work in "standalone" mode with a server simply consuming the outputs from the library. This isn't appropriate for a Blazor Web App, where the WebAssembly portion of the app is a logical part of the host and must behave more like a library. For example, the project doesn't expose the styles bundle (for example, BlazorSample.Client.styles.css
) and instead only provides the host with the project bundle, so that the host can include it in its own styles bundle.
Changing the value (Default
) of <StaticWebAssetProjectMode>
or removing the property from the .Client
project is not supported.
Static files in non-Development
environments
This section applies to server-side static files.
When running an app locally, static web assets are only enabled by default in the Development environment. To enable static files for environments other than Development during local development and testing (for example, Staging), call UseStaticWebAssets on the WebApplicationBuilder in the Program
file.
Warning
Call UseStaticWebAssets for the exact environment to prevent activating the feature in production, as it serves files from separate locations on disk other than from the project if called in a production environment. The example in this section checks for the Staging environment by calling IsStaging.
if (builder.Environment.IsStaging())
{
builder.WebHost.UseStaticWebAssets();
}
Prefix for Blazor WebAssembly assets
This section applies to Blazor Web Apps.
Use the WebAssemblyComponentsEndpointOptions.PathPrefix endpoint option to set the path string that indicates the prefix for Blazor WebAssembly assets. The path must correspond to a referenced Blazor WebAssembly application project.
endpoints.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode(options =>
options.PathPrefix = "{PATH PREFIX}");
In the preceding example, the {PATH PREFIX}
placeholder is the path prefix and must start with a forward slash (/
).
In the following example, the path prefix is set to /path-prefix
:
endpoints.MapRazorComponents<App>()
.AddInteractiveWebAssemblyRenderMode(options =>
options.PathPrefix = "/path-prefix");
Static web asset base path
This section applies to standalone Blazor WebAssembly apps.
By default, publishing the app places the app's static assets, including Blazor framework files (_framework
folder assets), at the root path (/
) in published output. The <StaticWebAssetBasePath>
property specified in the project file (.csproj
) sets the base path to a non-root path:
<PropertyGroup>
<StaticWebAssetBasePath>{PATH}</StaticWebAssetBasePath>
</PropertyGroup>
In the preceding example, the {PATH}
placeholder is the path.
Without setting the <StaticWebAssetBasePath>
property, a standalone app is published at /BlazorStandaloneSample/bin/Release/{TFM}/publish/wwwroot/
.
In the preceding example, the {TFM}
placeholder is the Target Framework Moniker (TFM) (for example, net6.0
).
If the <StaticWebAssetBasePath>
property in a standalone Blazor WebAssembly app sets the published static asset path to app1
, the root path to the app in published output is /app1
.
In the standalone Blazor WebAssembly app's project file (.csproj
):
<PropertyGroup>
<StaticWebAssetBasePath>app1</StaticWebAssetBasePath>
</PropertyGroup>
In published output, the path to the standalone Blazor WebAssembly app is /BlazorStandaloneSample/bin/Release/{TFM}/publish/wwwroot/app1/
.
In the preceding example, the {TFM}
placeholder is the Target Framework Moniker (TFM) (for example, net6.0
).
This section applies to standalone Blazor WebAssembly apps and hosted Blazor WebAssembly solutions.
By default, publishing the app places the app's static assets, including Blazor framework files (_framework
folder assets), at the root path (/
) in published output. The <StaticWebAssetBasePath>
property specified in the project file (.csproj
) sets the base path to a non-root path:
<PropertyGroup>
<StaticWebAssetBasePath>{PATH}</StaticWebAssetBasePath>
</PropertyGroup>
In the preceding example, the {PATH}
placeholder is the path.
Without setting the <StaticWebAssetBasePath>
property, the client app of a hosted solution or a standalone app is published at the following paths:
- In the Server project of a hosted Blazor WebAssembly solution:
/BlazorHostedSample/Server/bin/Release/{TFM}/publish/wwwroot/
- In a standalone Blazor WebAssembly app:
/BlazorStandaloneSample/bin/Release/{TFM}/publish/wwwroot/
If the <StaticWebAssetBasePath>
property in the Client project of a hosted Blazor WebAssembly app or in a standalone Blazor WebAssembly app sets the published static asset path to app1
, the root path to the app in published output is /app1
.
In the Client app's project file (.csproj
) or the standalone Blazor WebAssembly app's project file (.csproj
):
<PropertyGroup>
<StaticWebAssetBasePath>app1</StaticWebAssetBasePath>
</PropertyGroup>
In published output:
- Path to the client app in the Server project of a hosted Blazor WebAssembly solution:
/BlazorHostedSample/Server/bin/Release/{TFM}/publish/wwwroot/app1/
- Path to a standalone Blazor WebAssembly app:
/BlazorStandaloneSample/bin/Release/{TFM}/publish/wwwroot/app1/
The <StaticWebAssetBasePath>
property is most commonly used to control the paths to published static assets of multiple Blazor WebAssembly apps in a single hosted deployment. For more information, see Multiple hosted ASP.NET Core Blazor WebAssembly apps. The property is also effective in standalone Blazor WebAssembly apps.
In the preceding examples, the {TFM}
placeholder is the Target Framework Moniker (TFM) (for example, net6.0
).
File mappings and static file options
This section applies to server-side static files.
To create additional file mappings with a FileExtensionContentTypeProvider or configure other StaticFileOptions, use one of the following approaches. In the following examples, the {EXTENSION}
placeholder is the file extension, and the {CONTENT TYPE}
placeholder is the content type. The namespace for the following API is Microsoft.AspNetCore.StaticFiles.
Configure options through dependency injection (DI) in the
Program
file using StaticFileOptions:var provider = new FileExtensionContentTypeProvider(); provider.Mappings["{EXTENSION}"] = "{CONTENT TYPE}"; builder.Services.Configure<StaticFileOptions>(options => { options.ContentTypeProvider = provider; }); app.UseStaticFiles();
Pass the StaticFileOptions directly to UseStaticFiles in the
Program
file:var provider = new FileExtensionContentTypeProvider(); provider.Mappings["{EXTENSION}"] = "{CONTENT TYPE}"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider });
To create additional file mappings with a FileExtensionContentTypeProvider or configure other StaticFileOptions, use one of the following approaches. In the following examples, the {EXTENSION}
placeholder is the file extension, and the {CONTENT TYPE}
placeholder is the content type.
Configure options through dependency injection (DI) in the
Program
file using StaticFileOptions:using Microsoft.AspNetCore.StaticFiles; ... var provider = new FileExtensionContentTypeProvider(); provider.Mappings["{EXTENSION}"] = "{CONTENT TYPE}"; builder.Services.Configure<StaticFileOptions>(options => { options.ContentTypeProvider = provider; });
This approach configures the same file provider used to serve the Blazor script. Make sure that your custom configuration doesn't interfere with serving the Blazor script. For example, don't remove the mapping for JavaScript files by configuring the provider with
provider.Mappings.Remove(".js")
.Use two calls to UseStaticFiles in the
Program
file:- Configure the custom file provider in the first call with StaticFileOptions.
- The second middleware serves the Blazor script, which uses the default static files configuration provided by the Blazor framework.
using Microsoft.AspNetCore.StaticFiles; ... var provider = new FileExtensionContentTypeProvider(); provider.Mappings["{EXTENSION}"] = "{CONTENT TYPE}"; app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = provider }); app.UseStaticFiles();
You can avoid interfering with serving
_framework/blazor.server.js
by using MapWhen to execute a custom Static File Middleware:app.MapWhen(ctx => !ctx.Request.Path .StartsWithSegments("/_framework/blazor.server.js"), subApp => subApp.UseStaticFiles(new StaticFileOptions() { ... }));
Additional resources
Зворотний зв’язок
https://aka.ms/ContentUserFeedback.
Очікується незабаром: протягом 2024 року ми будемо припиняти використання механізму реєстрації проблем у GitHub для зворотного зв’язку щодо вмісту й замінювати його новою системою зворотного зв’язку. Докладніше:Надіслати й переглянути відгук про