ASP.Net Core: Use Shared Project to share static assets (css / js) between many projects
Here's how I solved this problem. I didn't use a Shared Project because I couldn't get that to work. Instead, I used PhysicalFileProvider
and it works like charm.
To do this, I created a new folder in src
. I called it assets
so my Solution Explorer looks something like this:
src/assets
src/Foo.Web1
src/Foo.Web2
test/Foo.Tests
I put all of the shared static assets (e.g. css, JavaScript, images) in /src/assets
. Now I map /src/assets
to the wwwroot/assets
folders in Foo.Web1
and Foo.Web2
projects using PhysicalFileProvider
. In Startup.cs
's Configure
method, I add this:
if (Env.IsDevelopment())
{
// app is IApplicationBuilder and Env is IHostingEnvironment
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Regex.Replace(Env.ContentRootPath, $"{Env.ApplicationName}$", "assets"))),
RequestPath = new PathString("/assets"),
OnPrepareResponse = ctx =>
{
// Optionally manipulate the response as you'd like. for example, I'm setting a no cache directive here for dev.
ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store, must-revalidate");
}
});
}
Now any request that comes to /assets
will be served from the /src/assets
folder that can be shared by Foo.Web1
and Foo.Web2
. All changes in /src/assets
will be reflected in real-time. This work great in dev, but when it comes to production, I don't do this. Instead, I copy the files from /src/assets
to Foo.Web1/wwwroot/assets
and Foo.Web2/wwwroot/assets
in my deployment script so this remapping doesn't need to happen.