TechieClues TechieClues
Updated date Apr 13, 2023
Learn how to serve static files from outside of the "wwwroot" folder in ASP.NET Core. This article provides a step-by-step guide with a sample program, output, and explanation on how to configure your ASP.NET Core application to serve static files from any location outside of the project directory

Introduction:

ASP.NET Core is a popular web framework that allows developers to build web applications using C# or other .NET languages. One of the features of ASP.NET Core is the ability to serve static files, such as CSS, JavaScript, images, and other assets, directly from the web server. By default, static files are served from the "wwwroot" folder in the project. However, in some cases, you may want to serve static files from a location outside of the "wwwroot" folder. In this article, we will explore how to serve static files from a location outside of the "wwwroot" folder in ASP.NET Core, along with a sample program, output, and explanation.

Prerequisites:

To follow along with this article, you will need the following:

  1. Visual Studio 2019 or later installed on your machine
  2. .NET Core 3.1 or later SDK installed on your machine
  3. Basic knowledge of ASP.NET Core and C#

Let's create a simple ASP.NET Core web application that serves static files from a location outside of the "wwwroot" folder.

Step 1: Create a new ASP.NET Core web application

Open Visual Studio and create a new ASP.NET Core web application.

Step 2: Install Microsoft.Extensions.FileProviders.Embedded NuGet package

In the newly created ASP.NET Core project, right-click on the project name in Solution Explorer and select "Manage NuGet Packages". Search for "Microsoft.Extensions.FileProviders.Embedded" and install the package.

Step 3: Create a folder to serve static files

Create a folder named "MyStaticFiles" in the root directory of your ASP.NET Core project. Inside the "MyStaticFiles" folder, add some static files, such as "styles.css" and "logo.png".

Step 4: Modify Program.cs

Open the "Program.cs" file in the root directory of your ASP.NET Core project and modify it as follows:

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

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

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                    webBuilder.UseStaticWebAssets();
                });
    }
}

The UseStaticWebAssets() method is called to enable the usage of embedded static web assets.

Step 5: Modify Startup.cs

Open the "Startup.cs" file in the root directory of your ASP.NET Core project and modify it as follows:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using System.IO;

namespace ServingStaticFilesOutsideWwwroot
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseStaticFiles();

            // Serve static files from outside of the wwwroot folder
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(env.ContentRootPath, "MyStaticFiles")),
                RequestPath = "/staticfiles"
            });

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }
    }
}

The UseStaticFiles() method is called to serve static files from the "wwwroot" folder, which is the default behavior in ASP.NET Core. Then, we use the UseStaticFiles() method again with a StaticFileOptions object to configure serving static files from outside of the "wwwroot" folder. We specify the FileProvider property to a PhysicalFileProvider object, which points to the "MyStaticFiles" folder we created earlier. We also set the RequestPath property to "/staticfiles", which is the URL path where the static files will be served from.

Step 6: Update Index.cshtml

Open the "Index.cshtml" file in the "Views/Home" folder of your ASP.NET Core project and update it as follows:

<!DOCTYPE html>
<html>
<head>
    <title>Static Files Outside wwwroot</title>
    <link rel="stylesheet" href="/staticfiles/styles.css" />
</head>
<body>
    <h1>Static Files Outside wwwroot</h1>
    <img src="/staticfiles/logo.png" alt="Logo" />
    <p>This is a sample ASP.NET Core web application that serves static files from outside of the wwwroot folder.</p>
</body>
</html>

In the <link> and <img> tags, we specify the URL path "/staticfiles" as the prefix to the static file names, which matches the RequestPath we configured earlier in the StaticFileOptions object.

Step 7: Run the application

Build and run the ASP.NET Core application. You should be able to access the static files "styles.css" and "logo.png" from the "MyStaticFiles" folder using the URL path "/staticfiles" in your browser. For example, if your application is running at "http://localhost:5000", you can access the "styles.css" file at "http://localhost:5000/staticfiles/styles.css" and the "logo.png" file at "http://localhost:5000/staticfiles/logo.png".

Output:

When you run the ASP.NET Core application and access it in a web browser, you should see the text "Static Files Outside wwwroot" displayed as a heading, along with an image and a paragraph of text. The CSS styles from the "styles.css" file should be applied to the page, and the image should be displayed correctly.

By default, ASP.NET Core serves static files from the "wwwroot" folder in the project. However, there may be scenarios where you want to serve static files from a different location outside of the "wwwroot" folder, such as when you want to share static files across multiple projects or when you want to serve static files from a location outside of the project directory.

To achieve this, we can use the UseStaticFiles() method multiple times in the Configure method of the Startup class, with different configurations. In our sample program, we first use the UseStaticFiles() method without any parameters to serve static files from the "wwwroot" folder, which is the default behavior. Then, we use the UseStaticFiles() method again with a StaticFileOptions object to configure serving static files from the "MyStaticFiles" folder outside of the "wwwroot" folder. We specify the FileProvider property to a PhysicalFileProvider object, which points to the "MyStaticFiles" folder, and set the RequestPath property to "/staticfiles" to specify the URL path where the static files will be served from.

In the "Index.cshtml" file, we update the URLs of the static files to include the "/staticfiles" prefix, which matches the RequestPath we configured earlier in the StaticFileOptions object. This ensures that the static files are properly served from the "MyStaticFiles" folder outside of the "wwwroot" folder.

Conclusion:

In conclusion, serving static files from outside of the "wwwroot" folder in ASP.NET Core can be achieved by using the UseStaticFiles() method multiple times in the Configure method of the Startup class with different configurations. By specifying the appropriate FileProvider and RequestPath properties in the StaticFileOptions object, we can serve static files from any location outside of the project directory. This can be useful in scenarios where we need to share static files across multiple projects or when we want to serve static files from a location outside of the "wwwroot" folder.

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!