AspNetCore.Docs/aspnetcore/blazor/fundamentals/static-files.md

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
Home
Privacy
Kestrel
appsettings.json
ASP.NET Core Identity
cookie
Cookie
Blazor
Blazor Server
Blazor WebAssembly
Identity
Let's Encrypt
Razor
SignalR
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 serving blazor.server.js. For example, don't remove the mapping for JavaScript files by configuring the provider with provider.Mappings.Remove(".js").

  • Use two calls to xref:Microsoft.AspNetCore.Builder.StaticFileExtensions.UseStaticFiles%2A in Startup.Configure (Startup.cs):

    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(){ ... })));