"ASP.NET Core Performance Series" static file Middleware

I. Overview

  Static files (such as HTML, CSS, images and JavaScript files) is a Web application directly to the client's file loaded directly. More than over the code in terms of the dynamic interaction of the program, in fact, the principles are the same (go Http protocol),

In ASP.NET Core require some configuration to provide these documents.

二、wwwroot

  Static file stored in the Web program item {ContentRoot} / under wwwroot directory, but can be changed by UseWebRoot path method. 

Web application project wwwroot folder by default there are multiple folders:

  • wwwroot
    • css
    • images
    • js

URI format for folder access images subfolder is http: // <server_address> / images  / <image_file_name>. For example,  HTTP: // localhost: 1189 / ImagesRF Royalty Free / banner.png .

  Open access static file by the following codes (set {ContentRoot} / wwwroot static file as the default working directory)

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();
}

Third, set the specified directory as static files working directory

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); //   wwwroot 目录

    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "the_path_to_yours")),
        RequestPath = "/GiveAName"
    });
}

  Note that access custom static file path changes: HTTP: // localhost: 1189 / GiveAName /images/banner.png

Fourth, to add client cache static files

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var cachePeriod = env.Production() ? "60000" : "600";
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            // 记得下面的引用:
            // using Microsoft.AspNetCore.Http;
            ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
        }
    });
}

  As above, in a production environment, we give static files add 60000 (ms) cache, namely: in one minute, the client would take the file from the browser local attention this way, directly update static files for a time was not even to the latest files.

 

 

Five ways to make use of PhysicalFile static file access can be authenticated

  Static files middleware allows the browser to access all static documents provided by the middleware static files (including files under wwwroot), we envision a practical application scenario, we upload a file to a specified directory, and this file only party you can access, then how authority to verify it?

[Authorize] // authentication 
public IActionResult UsersOwnPictrue ()
{
    var file = Path.Combine(Directory.GetCurrentDirectory(), 
                            "StaticFilesPath", "images", "my.svg");
    return PhysicalFile(file, "image/svg+xml");//返回静态文件
}

Six, using separate front and rear ends Development

  Development model developed separate front and rear ends, the front end of all interworking responsible for their own front end, not only that but also the back-end data before construction work has not started its own, ASP.NET Core middleware static files, and this just may be developed

Mode convergence, omitted here a million words, a little more concerned about the problem: how to set the project start page, how to set the default page for the front end of the project

public void Configure(IApplicationBuilder app)
{
   app.UseDefaultFiles (); // must be  UseStaticFiles invoked before  UseDefaultFilesUseDefaultFiles In fact for rewriting URL, does not provide the documents. 
    app.UseStaticFiles (); // These two steps 
}
Use UseDefaultFiles will use these documents as the default start page of the project:
 default .htm
 default .html
index.htm
index.html
public void Configure(IApplicationBuilder app)
{
    // use another file as the default static page file 
    DefaultFilesOptions Options = new new DefaultFilesOptions ();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add ( " .html under other wwwroot " );
    app.UseDefaultFiles(options);
    app.UseStaticFiles();
}

 

app.UseFileServer (); // can be any of the above two steps further

 

7, on UseFileServer

  UseFileServer integrated UseStaticFiles, UseDefaultFiles and UseDirectoryBrowser (optional, if enabled need services.AddDirectoryBrowser ()) function,

public void Configure(IApplicationBuilder app)
{
   
    app.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine (Directory.GetCurrentDirectory (), " Folders " )),
        RequestPath = " / Request Name " ,
        EnableDirectoryBrowsing = true
    });
}
Requests a connection Corresponding path
http: // <server_address> / request name /images/file1.png Folder /images/file1.png
http: // <server_address> / request name / Folder /default.html

Eight, open up the directory browsing

  This function is usually not open, it is more dangerous, browse through the directory, Web application users can view a list of files and directories in the specified directory. For security reasons, call  Startup.Configure UseDirectoryBrowser methods to enable directory browsing:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}
app.UseDirectoryBrowser ( new new DirectoryBrowserOptions // function to open wwwroot / images files for viewing
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/MyImages"
    });

Nine, specify the MIME type of the specified file type

public void Configure(IApplicationBuilder app)
{

    var provider = new FileExtensionContentTypeProvider();

    provider.Mappings [ " .rtf " ] = " file application / X-msdownload " ;
     // remove the specified file parsing 
    provider.Mappings.Remove ( " .mp4 " );
    ......
}
public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(new StaticFileOptions
    {
       // unknown type ContentType 
        ServeUnknownFileTypes = to true ,
        DefaultContentType = "bala/your type"
    });
}

 

Guess you like

Origin www.cnblogs.com/humble/p/12288903.html