Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active May 16, 2021 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manoj-choudhari-git/f06127073ffb2256d28c8bb524934dba to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/f06127073ffb2256d28c8bb524934dba to your computer and use it in GitHub Desktop.
.NET Core Web Applications - Static Files - Serve Static Files from any other directory
// Startup.cs
public class Startup
{
// some other code...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
// To Server CSS, JS from {CONTENT-ROOT}/WWWROOT
app.UseStaticFiles();
// To Serve images from {CONTENT-ROOT}/Images
app.UseStaticFiles(new StaticFileOptions
{
// physical path for the files accessed using /StaticFiles/ token
FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "Images")),
// This is the relative path from URL
RequestPath = "/StaticFiles"
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
// In File /home/index.cshtml, add img tag to access resource
// <img src="~/StaticFiles/some-image.jpg"/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment