2.7 KiB
title | author | description | monikerRange | ms.author | ms.custom | ms.date | no-loc | uid | ||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ASP.NET Core Blazor static files | guardrex | Learn how to configure and manage static files for Blazor apps. | >= aspnetcore-3.1 | riande | mvc | 01/27/2021 |
|
blazor/fundamentals/static-files |
ASP.NET Core Blazor static files
This article applies to Blazor Server.
To create additional file mappings with a xref:Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider or configure other xref:Microsoft.AspNetCore.Builder.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
Startup.ConfigureServices
(Startup.cs
) using xref:Microsoft.AspNetCore.Builder.StaticFileOptions:using Microsoft.AspNetCore.StaticFiles; ... var provider = new FileExtensionContentTypeProvider(); provider.Mappings["{EXTENSION}"] = "{CONTENT TYPE}"; services.Configure<StaticFileOptions>(options => { options.ContentTypeProvider = provider; });
Because this approach configures the same file provider used to serve
blazor.server.js
, make sure that your custom configuration doesn't interfere with servingblazor.server.js
. For example, don't remove the mapping for JavaScript files by configuring the provider withprovider.Mappings.Remove(".js")
. -
Use two calls to xref:Microsoft.AspNetCore.Builder.StaticFileExtensions.UseStaticFiles%2A in
Startup.Configure
(Startup.cs
):- Configure the custom file provider in the first call with xref:Microsoft.AspNetCore.Builder.StaticFileOptions.
- The second middleware serves
blazor.server.js
, 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 xref:Microsoft.AspNetCore.Builder.MapWhenExtensions.MapWhen%2A to execute a custom Static File Middleware:app.MapWhen(ctx => !ctx.Request.Path .StartsWithSegments("_framework/blazor.server.js", subApp => subApp.UseStaticFiles(new StaticFileOptions(){ ... })));