asp.net core series of static files

This explains static files in asp.net core (roughly translated to the official website).

Static files such as HTML, CSS, images and JavaScript. To directly access client, need to do some configuration.

A static Files .Serve (providing static files)

Static files stored in the project's web root directory. The default directory is <content_root> / wwwroot, but can UseWebRoot change the default directory method. More to view:  See  Content root  and  Web root  for More Information.

Application of web host must know the contents of the root directory.

WebHost.CreateDefaultBuilder method of setting the current directory to the root directory:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Static files can be a relative web root access path. For example, Web the Application project template in wwwroot contains several folders folder:

  • wwwroot
    • css
    • images
    • js

To images files in subdirectories of URI format: HTTP: // <server_address> / images / <image_file_name> . E.g, 

http://localhost:9189/images/banner3.svg.

If .NET Framework, add Microsoft.AspNetCore.StaticFiles package to the project. If .NET Core, Microsoft.AspNetCore.App contain this package.

Configuring middleware to provide services allow static files.

Inside of web root files 1.Serve (in the web root to provide the files service)

In Startup.Configure call UseStaticFiles methods:

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

The no-argument UseStaticFiles method marks the web root files can provide services. The following label references wwwroot / images / banner1.svg:

<img src="~/images/banner1.svg" alt="ASP.NET" class="img-responsive" />

In the above code, ~ / point Webroot , more information: the Web the root .

Like the above code, to use web root file, the need to point directly to the web root specific file under.

2.Serve files outside of web root ( the web root to providing file services )

Consider the following directory hierarchy will be web root out MyStaticFiles provide file services.

By configuring static files middleware (the Static File Middleware), so that the request can be made banner1.svg file:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

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

In the above code, MyStaticFiles directory by StaticFiles the URI is exposed. A to http: // <server_address> /StaticFiles/images/banner1.svg request can be obtained banner1.svg file. 

The following tag references MyStaticFiles / images / banner1.svg file:

<img src="~/StaticFiles/images/banner1.svg" alt="ASP.NET" class="img-responsive" />

3.Set HTTP response headers ( set HTTP response headers )

StaticFileOptions object can be used to set the HTTP response headers (HTTP response headers ) . In addition to configuring a static file serving web root, the following code sets the Cache-Control header:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var cachePeriod = env.IsDevelopment() ? "600" : "604800";
    app.UseStaticFiles(new StaticFileOptions
    {
        OnPrepareResponse = ctx =>
        {
            // Requires the following import:
            // using Microsoft.AspNetCore.Http;
            ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
        }
    });
}

HeaderDictionaryExtensions.Append method is present in Microsoft.AspNetCore.Http package.

This file can be cached in the development environment 10 Fenzhong (600 Miao ) .

Two .Static file authorization ( static file authorization )

Static files middleware does not provide authorization checks. Any file that provides services, including wwwroot under, are publicly accessible.

To provide file services-based authorization:

  • They are stored in wwwroot outside and static files to any directory for the middleware can be reached
  • Certified action to provide their methods. Returns a FileResult objects:
[Authorize]
public IActionResult BannerImage()
{
    var file = Path.Combine(Directory.GetCurrentDirectory(), 
                            "MyStaticFiles", "images", "banner1.svg");

    return PhysicalFile(file, "image/svg+xml");
}

Three .Enable directory browsing (allow directory browsing )

Directory allows you to browse the web users on the applications to see a list of directories and files in the directory specified. Directory browsing for security reasons is disabled by default. Can Startup.Configure call method UseDirectoryBrowser methods to allow directory browsing:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

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

    app.UseDirectoryBrowser(new DirectoryBrowserOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/MyImages"
    });
}

By Startup.ConfigureServices call AddDirectoryBrowser to add the necessary services:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}

The above code allows wwwroot / images directory browsing directory through http: // <server_address> / MyImages

Use this link to get to each file and directory:

Some security risk to allow directory browsing, you can see Considerations

Note the following example of two UseStaticFiles calls. The first call allows wwwroot folder provides static files.

The second call allows wwwroot / images folder using the directory browser, through HTTP: // <server_address> / MyImages : 

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

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

    app.UseDirectoryBrowser(new DirectoryBrowserOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/MyImages"
    });
}

Four .Serve a default document ( a default document )

Setting a default home page page provided to the start page viewers a logical (starting point), when you visit the site. To provide a default user does not require detailed modification URI page, you need to Startup.Configure call UseDefaultFiles methods:

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

Emphasis

UseDefaultFiles must UseStaticFiles be called before to provide the default file. UseDefaultFiles is a URL rewriter, it does not really provide file services. Allowing the Static File Middleware by UseStaticFiles to provide services.

Use UseDefaultFiles , you request a search folder:

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

The first file in the list will be found to provide the service, as if the request is modified as detailed.

The following code to change the default file name mydefault.html:

public void Configure(IApplicationBuilder app)
{
    // Serve my app-specific default file, if present.
    DefaultFilesOptions options = new DefaultFilesOptions();
    options.DefaultFileNames.Clear();
    options.DefaultFileNames.Add("mydefault.html");
    app.UseDefaultFiles(options);
    app.UseStaticFiles();
}

Five .UseFileServer ( using a file server )

UseFileServer combines UseStaticFiles , UseDefaultFiles, and UseDirectoryBrowser functions.

The following code allows the service to provide static files and the default file. Directory browsing is not allowed.

app.UseFileServer();

The following code is based on the no-argument overloaded, browse the directory by allowing:

app.UseFileServer(enableDirectoryBrowsing: true);

Consider the following directory hierarchy:

The following code allows MyStaticFiles static file, the default file and directory browsing:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseFileServer(new FileServerOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "MyStaticFiles")),
        RequestPath = "/StaticFiles",
        EnableDirectoryBrowsing = true
    });
}

When EnableDirectoryBrowsing attribute value is true when, AddDirectoryBrowser must be called:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDirectoryBrowser();
}

Use file-level and before the code, URLs interpreted as follows:

If MyStaticFiles directory, there is no default file name exists, HTTP: // <server_address> / StaticFiles

Returns the directory listing is clicked on the link:

六.FileExtensionContentTypeProvider

FileExtensionContentTypeProvider class contains a mapping property, this property provides a mapping file extensions to MIME content types mapping. The following code, several file extension (file extensions) are registered as known in the MIME types . .rtf extension was replaced, and .mp4 been removed.

public void Configure(IApplicationBuilder app)
{
    // 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
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/MyImages",
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images")),
        RequestPath = "/MyImages"
    });
}

更多:MIME content types.  

七.Non-standard content types(非标准类型)

Static File Middleware 理解几乎400个已知的文件类型(file content types).如果用户请求一个未知的文件类型,Static File Middleware 会传递这个请求到管道上的下一个中间件。如果没有中间件可以处理这个请求,一个404 Not Found 响应会被返回。如果目录浏览被允许,在目录列表中,一个到这个文件的链接会被展示。

下面的代码允许提供未知的类型,并且渲染未知的文件为一个图片:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(new StaticFileOptions
    {
        ServeUnknownFileTypes = true,
        DefaultContentType = "image/png"
    });
}

使用上面的代码,一个对未知文件类型的请求会作为一个图片返回。

警告:允许ServeUnknownFileTypes是有安全风险的。它默认是被禁用的,并且这种用法不推荐使用。FileExtensionContentTypeProvider提供一个更安全的可选的方式来提供带有non-standard extensions扩展的文件。

Considerations(考虑)

  • 使用UseDirectoryBrowserUseStaticFiles来暴露内容的URLs是适合于大小写敏感并且在文件系统下有字符限制。例如,Windows是大小写敏感的,macOSLinux不是。
  • ASP.NET Core 应用部署在IIS上,使用ASP.NET Core Module 来发送所有的请求到应用,包括静态文件请求。IIS静态文件处理器(IIS static file handler)没有使用。它没有机会处理请求在它们被这个模块处理之前。
  • IIS Manager中移除IIS static file handler的步骤,在服务器或者网站层次:
    1. 导航到Modules功能
    2. 选择列表中的StaticFileModule
    3. 点击删除

警告:如果IIS文件处理器被允许并且ASP.NET Core Module没有被正确配置,静态文件会提供服务。这会发生,例如,如果web.config文件没有被部署。

  • 存放代码文件(包括.cs.cshtml)在项目的web root的外面。逻辑上的分开应该被建立,在应用的客户端内容和服务端代码(app’s client-side content and server-based code).这可以预防服务端代码被泄露。

地址:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-2.2

 

Guess you like

Origin www.cnblogs.com/Vincent-yuan/p/11247511.html