-
Notifications
You must be signed in to change notification settings - Fork 68
Description
Summary
Add the System.Web.VirtualPathUtility class to systemweb adapters to allow the use from AspNet Core and class libraries whilst migrating an application.
Motivation and goals
Within our application we make use of this class, mainly to handle dynamic paths and in areas where we need to return absolute paths regardless of the request url (e.g. in webapi call, middleware, partial views etc.).
In scope
Handle the following methods on System.Web.VirtualPathUtility
namespace System.Web;
public static class VirtualPathUtility
{
public static string Combine(string basePath, string relativePath);
public static string GetDirectory(string virtualPath);
public static string GetExtension(string virtualPath);
public static string GetFileName(string virtualPath);
public static bool IsAppRelative(string virtualPath);
public static string MakeRelative(string fromPath, string toPath);
public static string ToAbsolute(string virtualPath);
public static string ToAppRelative(string virtualPath);
}Out of scope
The overloads which allow you to include the applicationPath would not be needed (at least not for my project).
Risks / unknowns
Most of these functions relate to translating paths starting ~/ to the base url which should be available with #81 as HttpRuntime.AppDomainAppVirtualPath.
The naïve implementation could use UrlBuilder and/or combinations of StartsWith and SubString to implement the main functions.
The Get* methods would probably need to get the IFileProvider interface registered to get the appropriate physical file paths and names for virtual paths.
GetFileName and GetExtension should work regardless of whether the file resolved to a physical file or not.
Most of these functions are no longer in use in web applications since it is now common to have each web application at the root, rather than installed as a sub site in IIS so this is largely for legacy projects where these abstractions have not yet been removed, or where configuration files or similar use 'app relative paths' like ~/App_Data/myconfig.json
Examples
public static class ThemeClaims
{
public static string GetThemeOrDefault(this ClaimsIdentity identity, string @default = "default")
{
var claim = identity?.FindFirst("myapp:Theme");
if (claim is null) return @default;
return claim.Value;
}
}
public class ThemeModel
{
public string Theme { get; set; } =
(System.Web.HttpContext.Current.User?.Identity as ClaimsIdentity).GetThemeOrDefault();
public string ThemeURL {
get => System.Web.VirtualPathUtility
.ToAbsolute($"~/custom/themes/{Theme}/theme.css");
}
}