Static files, such as HTML, CSS, pictures and JavaScript, will be directly provided to clients by asp.net core applications.

Static file service

//Install staticfiles package
Install-Package Microsoft.AspNetCore.StaticFiles

In the application, we can enable the static file service by configuring the staticfiles middleware, and add the staticfiles middleware to the pipeline:

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

Static files are usually located in the web root (/wwwroot) folder. We usually set the current directory of the project as content root, so that the web root of the project can be defined in the development phase.

  • http://(app)/(fileName)
  • http://localhost:9189/1.jpg
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
        RequestPath = new PathString("/StaticFiles")
    });
}

Static files can also be saved in any folder under the root directory of the website, and can be accessed through the relative root path.

  • http://(app)/StaticFiles/(fileName)
  • http://localhost:9189/StaticFiles/1.jpg

Set response header

Staticfileoptions() can set the response header. For example, the following code sets the static file service to use the wwwroot folder and set cache control to cache static resources for 10 minutes (600 seconds):

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles(new StaticFileOptions()
    {
        OnPrepareResponse = ctx =>
        {
            ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600");
        }
    });
}

The HeaderDictionaryExtensions.Append extension method can be used by installing the Microsoft. Aspnetcore. HTTP package.

Enable directory browsing

DirectoryBrowser allows site users to see a list of directories and files in the specified directory. For security reasons, directory access is disabled by default.
Call in Startup.Configure UseDirectoryBrowser extension method enables browsing of network application directory:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles")),
        RequestPath = new PathString("/StaticFiles")
    });
}

Invoke the required service AddDirectoryBrowser in Startup.ConfigureServices.

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

The above code allows access to links to all files and folders in the staticfiles file:

Provide a default file

You can configure a default page for your site by calling UseDefaultFiles at Startup.Configure.

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

Before calling UseStaticFiles, the UseDefaultFiles, the UseDefaultFiles is only a URL Rewrite, but actually does not provide a file. The StaticFiles middleware must be used to provide the file.

Files searched by default using UseDefaultFiles:

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

The following code shows how to set the default file to 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();
}

File server

The function of UseFileServer combines UseStaticFiles, UseDefaultFiles, UseDirectoryBrowser.

The following code allows access to static and default files, but does not allow browsing directories:

app.UseFileServer();

The following code allows access to static files, default file and directory browsing:

app.UseFileServer(enableDirectoryBrowsing: true);

If you want to have a static file server outside the web root, you can configure the static file middleware:

public void Configure(IApplicationBuilder app)
{
    app.UseFileServer(new FileServerOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles2")),
        RequestPath = new PathString("/StaticFiles2")
    });
}

When EnableDirectoryBrowsing is set to true, enable directory browsing:

public void Configure(IApplicationBuilder app)
{
    app.UseFileServer(new FileServerOptions()
    {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"MyStaticFiles2")),
        RequestPath = new PathString("/StaticFiles2"),
        EnableDirectoryBrowsing = true
    });
}

And you need to invoke the required service AddDirectoryBrowser in Startup.ConfigureServices.

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

FileExtensionContentTypeProvider

The FileExtensionContentTypeProvider class contains a collection that maps file extensions to mime content types. In the following example, multiple file extensions are registered as known MIME types, ". rtf" is replaced and ". mp4" is removed.

public void ConfigureServices(IServiceCollection services)
{
    // 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(), @"MyStaticFiles3")),
        RequestPath = new PathString("/StaticFiles3"),
        ContentTypeProvider = provider
    });
}

View MIME content type

Non standard content types

Asp.net core staticfiles middleware can support more than 400 known file content types. If the user requests an unknown file type, the static file middleware will return an HTTP 404 (not found) response. If directory browsing is enabled, the link to the file will be displayed, but the URI will return an HTTP 404 error.

The following code treats unrecognized types and files as pictures:

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

According to the above code, a file request of unknown content type will return a picture.

Precautions

Open ServeUnknownFileTypes There is a safety risk, please stop this idea。 FileExtensionContentTypeProvider (explained below) provides a safer alternative to non-standard extensions。
There may be leaks in UseDirectoryBrowser and UseStaticFiles. Do not enable directory browsing in the production environment. Be careful which directories have UseStaticFiles or UseDirectoryBrowser enabled (so that all subdirectories can be accessed). It is recommended to place public content in a directory such as <content root>/wwwroot, away from application views, configuration files, etc.

  • Whether URLs of files exposed with usedirectorybrowser and usestaticfiles are case sensitive and character restrictions are subject to the underlying file system. For example, windows is not case sensitive, but Mac OS and Linux are case sensitive.
  • The asp.net core application hosted in IIS uses the asp.net core module to forward all requests, including static files, to the application. The IIS static file handler is not used because it does not have any chance to process the request until it is processed by the asp.net core module.
  • The following steps remove the IIS static file handler (at the server or web site level):
    1.Navigate to module function
    2.Select staticfilemodule from the list
    3.Click delete in the operation sidebar

If the IIS static file handler is turned on and the asp.net core module (ANCM) is not properly configured (for example, web.config is not deployed), static files will also be provided.

  • The code files (including C ා and razor) should be placed outside the web root (the default is wwwroot) of the application project. This will ensure that the application you create clearly isolates the client side and server side source code, which prevents the server side code from being leaked.
Like The Article To View All

All Comments

Leave a Reply Cancel Reply

Tips: Your email address will not be disclosed!

If you can't see clearly,please click to change...