Static files in ASP.NET Core

Static Files

Static Files include HTML, CSS, images, JavaScript, and other static resource files.
That is, the content of the website itself.

Static Files Service

Static Files are kept in the project's Web Root directory, the wwwroot folder.
The wwwroot directory is a subdirectory of Content Root, which also includes other code files, .exe and .dll files.
The structure of the wwwroot folder is as follows:

  • css
  • js
  • lib
  • images
    • 1.jpg

After calling UseStaticFiles to enable the static file service when the App starts, the wwwroot directory will be mapped to https:///

app.UseStaticFiles();

This image file can be accessed through the url https://localhost:5001/images/1.jpg.

Map other directories

If you want to map other directories to https:///otherroot/images/1.jpg, such as

  • wwwroot
    • css
    • images
    • js
  • otherroot
    • images
      • 1.jpg

It can be mapped like this:

app.UseStaticFiles(new StaticFileOptions
{
    
    
    FileProvider = new PhysicalFileProvider(
           Path.Combine(builder.Environment.ContentRootPath, "otherroot")),
    RequestPath = "/otherroot",
    OnPrepareResponse = ctx =>
    {
    
    
        var cacheMaxAgeOneWeek = (60 * 60 * 24 * 7).ToString();
        ctx.Context.Response.Headers.Append(
            "Cache-Control", $"public, max-age={
      
      cacheMaxAgeOneWeek}"); //添加过期时间
    }
});

Then you can refer to it in html code like this:

<img src="~/otherroot/images/1.png" class="img" asp-append-version="true" alt="Test">

Set access permissions for Static Files

3 conditions need to be met:

  • not saved under wwwroot
  • Call UseAuthorization first, then call UseStaticFiles
  • Set fallback authorization policy
builder.Services.AddAuthorization(options =>
{
    
    
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();
});

to prohibit anonymous access to these files.

list file directories

Directory Browsing service can list all files in a directory.
Can be enabled via AddDirectoryBrowser():

builder.Services.AddDirectoryBrowser();
var fileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.WebRootPath, "MyImages"));
var requestPath = "/MyImages";
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    
    
    FileProvider = fileProvider,
    RequestPath = requestPath
});

use default file

After using app.UseDefaultFiles(),

app.UseDefaultFiles();

These files will be searched in sequence under wwwroot as the entry

  • default.htm
  • default.html
  • index.htm
  • index.html

You can also specify the file name mydefault.html:

var options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("mydefault.html");
app.UseDefaultFiles(options);

You are on FileServer

app.UseFileServer is a combination of UseStaticFiles, UseDefaultFiles or UseDirectoryBrowser.

builder.Services.AddDirectoryBrowser();
app.UseFileServer(enableDirectoryBrowsing: true);

The above code will enable UseStaticFiles, UseDefaultFiles, and DirectoryBrowsing.

FileExtensionContentTypeProvider

The Mappings property of FileExtensionContentTypeProvider can map file extensions to MIME Content Types.

// Set up custom content types - associating file extension to MIME type
var provider = new FileExtensionContentTypeProvider();
// Add new mappings
provider.Mappings[".myapp"] = "application/x-msdownload";
provider.Mappings[".htm3"] = "text/html";
provider.Mappings[".image"] = "image/png";
// Replace an existing mapping
provider.Mappings[".rtf"] = "application/x-msdownload";
// Remove MP4 videos.
provider.Mappings.Remove(".mp4");
app.UseStaticFiles(new StaticFileOptions
{
    
    
    ContentTypeProvider = provider
});

Guess you like

Origin blog.csdn.net/cuit/article/details/132577692
Recommended