Last active
May 16, 2021 21:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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