Tuesday, July 11, 2023

ASP.NET Core UseStaticFiles method


ASP.NET Core UseStaticFiles is an extension method of IApplicationBuilder. This is used in HTTP pipeline to enable the service of static files in the application. The HTTP request for a static file cannot be handled by the application unless this method is used during HTTP pipeline configuration.

In ASP.NET Core, static files are served from the web root path specified in WebRootPath or WebRootFileProvider. The default web root is the 'wwwroot' folder in solution explorer.

The UseStaticFiles has three overloaded versions.
namespace Microsoft.AspNetCore.Builder
{
    // Extension methods for the StaticFileMiddleware
    public static class StaticFileExtensions
    {
        //     Enables static file serving for the current request path
        public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app);

        //     Enables static file serving for the given request path
        public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, string requestPath);

        //     Enables static file serving with the given options
        public static IApplicationBuilder UseStaticFiles(this IApplicationBuilder app, StaticFileOptions options);
    }
}

Three versions

  • The first version enables the service for static files from the wwwroot folder, and the current request path is not required as it is the current domain path. 
  • The second version allows to add a request path string as its parameter. This request path is added after the current domain path. This is a dummy string not representing any folder but business logic.
  • The third version allows to add options to serve the static files.
UseStaticFiles Version2
Request Path: We are using .NET5.0 to explain it. Look at the following code which is in Configure method of Startup class. The request path parameter is used in 2nd version of UseStaticFiles. Because of request path parameter, any static file can be accessed from wwwroot just by appending MyCss after the domain name in the URL. Both search.png and upload.png are in the same wwwroot folder in images subfolder but can be accessed using either of the following URL.
            app.UseStaticFiles(); // https://localhost:44309/images/search.png
            app.UseStaticFiles("/MyCss"); //https://localhost:44309/MyCss/images/upload.png
The MyCss is a request path parameter in the UseStaticFiles. Note that MyCss is not a folder in the wwwroot.
UseStaticFiles Version3
StaticFileOptions: The files can be served based on different options such as content-types, file system used, request path, web root folder etc. We use StaticFileOptions class to meet these options as required. Look at the following code in which StaticFileOptions object is used with its various properties to access files from NewWebRoot folder. Note that we do not use UseWebRoot method to configure the web root in the Program class.
            app.UseStaticFiles(new StaticFileOptions()
            {
                DefaultContentType = "text/html",
                FileProvider = new PhysicalFileProvider(Path.Combine(System.IO.Directory.GetCurrentDirectory(), "NewWebRoot")),
                RequestPath = "/Sales"

            });
Create a folder Images in NewWebRoot folder and place an image in the Images folder. Run the application. Now use the URL https://localhost:44391/sales/Images/happy.jpg in the address bar. Press Enter. You get the image file happy.jpg placed in the Images folder. Note that in this example, request path sales is mandatory.

FileProvider property of StaticFileOptions class is used to locate resources such as page, view, static files such as images, xml, files, CSS files etc. from the root path specified as parameter. 
  • The Microsoft.Extensions.FileProviders namespace is used for different file providers.
  • File Provider three Interfaces are IFileInfo, IDirectoryContents, IChangeToken. 
  • The primary interface is IFileProvider which is used to obtain file and directory information and change in them. 
  1. GetDirectoryContents(String) enumerates a directory at the given path, if any.
  2. GetFileInfo(String) locates a file at the given path.
  3. Watch(String) creates a IChangeToken for the specified filter.
Look at the following code which includes all 3 versions of UseStaticFiles.

            // https://localhost:44309/images/search.png
            app.UseStaticFiles(); 
            //https://localhost:44309/MyCss/images/upload.png
            app.UseStaticFiles("/MyCss"); 
            //https://localhost:44309/mystaticfiles/products.xml
            app.UseStaticFiles(new StaticFileOptions
            {
               FileProvider= new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "NewWebRoot")),
               RequestPath ="/MyStaticFiles"
            });

No comments:

Post a Comment

Hot Topics