Created
August 27, 2023 16:22
-
-
Save dmorosinotto/ca83055a709659a7175edc347695f64c to your computer and use it in GitHub Desktop.
MapPath() Extension Method in ASP.NET: Map Physical Paths with an HttpContext.
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
//ORIGINAL CODE BY RICK STRAHL https://weblog.west-wind.com/posts/2023/Aug/15/Map-Physical-Paths-with-an-HttpContextMapPath-Extension-Method-in-ASPNET | |
public static class HttpContextExtensions | |
{ | |
static string WebRootPath { get; set; } | |
static string ContentRootPath { get; set; } | |
/// <summary> | |
/// Maps a virtual or relative path to a physical path in a Web site, | |
/// using the WebRootPath as the base path (ie. the `wwwroot` folder) | |
/// </summary> | |
/// <param name="context">HttpContext instance</param> | |
/// <param name="relativePath">Site relative path using either `~` or `/` as root indicator</param> | |
/// <param name="host">Optional - IHostingEnvironment instance. If not passed retrieved from RequestServices DI</param> | |
/// <param name="basePath">Optional - Optional physical base path. By default host.WebRootPath</param> | |
/// <param name="useAppBasePath">Optional - if true returns the launch folder rather than the wwwroot folder</param> | |
/// <returns>physical path of the relative path</returns> | |
public static string MapPath(this HttpContext context, | |
string relativePath = null, | |
IWebHostEnvironment host = null, | |
string basePath = null, | |
bool useAppBasePath = false) | |
{ | |
if (string.IsNullOrEmpty(relativePath)) | |
relativePath = "/"; | |
// Ignore absolute paths | |
if (relativePath.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || | |
relativePath.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) | |
return relativePath; | |
if (string.IsNullOrEmpty(basePath)) | |
{ | |
if(string.IsNullOrEmpty(WebRootPath) || string.IsNullOrEmpty(ContentRootPath)) | |
{ | |
//In ASP.NET Core versions prior to 3.0, there was no IWebHostEnvironment. | |
//Instead you had to use IHostingEnvironment to access ContentRootPath and WebRootPath. | |
host ??= context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment; | |
WebRootPath = host.WebRootPath; | |
ContentRootPath = host.ContentRootPath; | |
} | |
basePath = (useAppBasePath ? ContentRootPath : WebRootPath).TrimEnd('/', '\\'); | |
} | |
relativePath = relativePath.TrimStart('~', '/', '\\'); | |
string path = Path.Combine(basePath, relativePath); | |
string slash = Path.DirectorySeparatorChar.ToString(); | |
return path | |
.Replace("/", slash) | |
.Replace("\\", slash) | |
.Replace(slash + slash, slash); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment