Monday 28 September 2020

ASP.NET Core - Serving Static files

 Here, we will learn how to serve static files such as html, JavaScript, CSS, or image files on HTTP request without any server-side processing.

ASP.NET Core application cannot serve static files by default. We must include Microsoft.AspNetCore.StaticFiles middleware in the request pipeline.

Using StaticFiles Middleware

By default, all the static files of a web application should be located in the web root folder wwwroot. To understand this, let's create a simple default.html in the wwwroot folder with the following content.

Now, to serve the above Default.html static file, we must add StaticFiles middleware in the Configure() method of Startup file as shown below.
public class Startup
{
    public Startup()
    {
    } 
 
    public void Configure(IApplicationBuilder appIHostingEnvironment env)
    {
        app.UseStaticFiles();

        app.Run(async (context=>
        {
            await context.Response.WriteAsync("Hello World");
        });
    }
}

As you can see above, the app.UseStaticFiles() method adds StaticFiles middleware into the request pipeline. The UseStaticFiles is an extension method included in the StaticFiles middleware so that we can easily configure it.

Now, open the browser and send http request http://localhost:<port>/default.html which will display default.html as a response as shown below.

Serving HTML File

This way we can serve any other file stored in wwwroot folder or sub-folder.

Suppose, you want to serve files from the outside of web root folder (wwwroot). For example, you include images in the following Images folder as shown below.


Now, specify StaticFileOptions parameter in the UseStaticFiles method to serve images from the Images folder as shown below.
public void Configure(IApplicationBuilder appIHostingEnvironment env)
{
    app.UseStaticFiles(); // For the wwwroot folder

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
                            Path.Combine(Directory.GetCurrentDirectory(), @"Images")),
                            RequestPath = new PathString("/app-images")
    });
}

As you can see, we used FileProvider option to specify Images folder from which static files will be served. The RequestPath option specifies the relative path in the URL which maps to the static folder.

Now, a request to http://localhost/app-images/MyImage.png will serve the MyImage.png file.

Set Default File

As we have seen above, default.html or test.js was served on the specific request for it. However, what if we want to serve default html file on the root request?

Currently, when you send http://localhost:<port> request, it will be handled by run method and display the following result.

To serve default.html on the root request http://localhost:<port>, call UseDefaultFiles() method before UseStaticFiles() in the Configure method as shown below.

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

    app.Run(async (context=>
    {
       await context.Response.WriteAsync("Hello World");
    });
}

The UseDefaultFiles configures the DefaultFiles middleware which is a part of StaticFiles middleware. This will automatically serve html file named default.html, default.htm, index.html or index.htm on the http request http://localhost:<port>. The above example will display default.html file on http://localhost:<port> request.

Note:- Order of middleware is very important. app.UseDefaultFiles() should be added before app.UseStaticFiles() in the request pipeline.

FileServer

The FileServer middleware combines the functionalities of UseDefaultFiles and UseStaticFiles middlware. So, instead of using both the middlware, just use UseFileServer in the Configure method.

UseFileServer = UseDefaultFiles + UseStaticFiles

Thus, we can serve static files on http requests.

Reference: www.tutorialsteacher.comhttps://docs.microsoft.com

1 comment:

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives