ASP.NET Core: Access node_modules folder inside ASP.NET Core Project

Standard

We are not supposed to access files from outside of wwwroot. The wwwroot folder is the public folder that’s accessible from outside, when you host it.

The typical publishing process is, that you have a gulp or grunt task that runs when your ASP.NET webproject is compiled or published, it would run the tasks there and copy over the necessary files inside wwwroot.

However In order to access node_module inside your ASP.NET Core project without involving Gulp tasks is to manually register node_modules folder inside Configure() method inside Startup.cs class

Include below namespaces inside Startup.cs class

using Microsoft.Extensions.FileProviders;
using System.IO;

Serve other folders by using app.UseStaticFiles.

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //rest of the code

    ServeFromDirectory(app, env, "node_modules");
    
    app.UseStaticFiles();

    //rest of the code
}

public void ServeFromDirectory(IApplicationBuilder app, IHostingEnvironment env, string path)
{
    app.UseStaticFiles(new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(env.ContentRootPath, path)
        ),
        RequestPath = "/" + path
    });
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s