Inorder to handle 404 request from a client side application, the Microsoft.AspNetCore.SpaServices NuGet package includes a routing helper called MapSpaFallbackRoute to avoid to navigate to an invalid url. In the below code it’s always fallback to the home page.
Here I am going to explain how to serve static files from the nodemodules
Step 1 : Add a NPM package.json file
Right click on Visual Studio Add > NewItem and select NPM configuration files and add to the project.
Once you save the package.json , you can see the npm package in project dependencies and also node modules are downloaded in to the project directory.You can include the node_modules folder in to your VS Project by clicking show all files and include in to the project.
Step 3 : Create Middle ware to serve the files from node_modules directory
In order to create your own middleware , First you have to create an extension method for the builder to serve the files from the node_modules directory
public static class ApplicationBuilderExtensions
public static IApplicationBuilder UseNodeModules(this IApplicationBuilder app,string rootPath)
//Combine the rootpath to the node_modules to get the absolute path
var path = Path.Combine(rootPath, "node_modules");
var fileProvider = new PhysicalFileProvider(path);
var options = new StaticFileOptions();
options.RequestPath = "/node_modules";
options.FileProvider = fileProvider;
When you set a RequestPath , static files Middleware only try to respond to request starts with node_modules.
FileProvider is where does it goes to FileSystem to look for the file.
Finally Call the method by passing the application rootPath
public class Startup
public void ConfigureServices(IServiceCollection services)
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IConfiguration configuration ,ILogger logger)
private void ConfigureRoutes(IRouteBuilder routeBuilder)
Note : Please make sure the namespaces for extension method and startup.cs class are same. This is the approach that Microsoft uses to resolve the extension method for IApplicationBuilder to ensure method is more diiscoverable.
A WebHost builder is an object , which is responsible for setting up the web server environment.These settings are completely customizable by writing our own builder. By default Web host builder is using Kestrel web server, which is a cross platform web server supported by .NET Core. This Webserver will listen all the http request connections. Also This builder set ups IIS integration. If your application are running under IIS , it is the integration that allows IIS to pass through Windows Credentials to the Kestrel server.