Serving Static Files Outside wwwroot In ASP.NET Core
In 99% of cases, static files you want served for your website will be able to live in the wwwroot folder. But in that rare 1% use case that you need to have static files littered throughout your project (Or you dislike having a wwwroot folder nonstop!), what can you do?
First off, you will need the StaticFiles nuget package to be able to serve files at all. So run the following from your nuget package manager :
Install-Package Microsoft.AspNetCore.StaticFiles
In your startup.cs, you would typically see something similar to the following where the “UseStaticFiles” call allows you to serve files from your wwwroot folder :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseMvcWithDefaultRoute(); }
But you can actually add multiple calls to StaticFiles each with it’s own file location :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"content", @"js")), RequestPath = new PathString("/content/js") }); app.UseMvcWithDefaultRoute(); }
We leave the original StaticFiles call in there so that the wwwroot is still used to serve static files if we want (Although if you are intending to never use it, you can remove that call completely), but we can add subsequent calls to the middleware for each additional static content folder.
The FileProvider parameter tells the middleware where it can find the physical files, and the RequestPath is the actual URL that a browser should go to to reach the static files. In this example if we we went to something like www.mysite.com/content/js/site.js, we would be served static files.
Modifying the RequestPath can come in handy, consider the following :
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"content", @"js")), RequestPath = new PathString("/js") }); app.UseMvcWithDefaultRoute(); }
In this example our physical folder hasn’t changed, but the request path is now simply /js rather than /content/js. You can use this to essentially rewrite public urls for your static content (Which can come in handy if you end up moving around the actual physical folder).
No comments