Skip to content

Instantly share code, notes, and snippets.

@solrevdev
Last active August 16, 2023 10:46
Show Gist options
  • Save solrevdev/76228f19912f196e93fa4f7f8650a182 to your computer and use it in GitHub Desktop.
Save solrevdev/76228f19912f196e93fa4f7f8650a182 to your computer and use it in GitHub Desktop.
Map Physical Paths with an HttpContext.MapPath() Extension Method in ASP.NET (via By Rick Strahl)
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
/// <summary>
/// Provides extension methods for the HttpContext class.
/// </summary>
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))
{
host ??= context.RequestServices.GetService(typeof(IWebHostEnvironment)) as IWebHostEnvironment;
WebRootPath = host.WebRootPath;
ContentRootPath = host.ContentRootPath;
}
basePath = useAppBasePath ? ContentRootPath.TrimEnd('/', '\\') : WebRootPath;
}
relativePath = relativePath.TrimStart('~', '/', '\\');
string path = Path.Combine(basePath, relativePath);
string slash = Path.DirectorySeparatorChar.ToString();
return path
.Replace("/", slash)
.Replace("\\", slash)
.Replace(slash + slash, slash);
}
}
// Via https://weblog.west-wind.com/posts/2023/Aug/15/Map-Physical-Paths-with-an-HttpContextMapPath-Extension-Method-in-ASPNET
// cSpell: ignore wwwroot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment