Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net Core Replacement for VirtualPathUtility

Is there a replacement for VirtualPathUtility.ToAbsolute in ASP.Net Core? It doesn't seem to be available.

I'm wanting to convert a relative path e.g. "~/bob" into an absolute path, e.g. "/app/bob".

I'm trying to do this from a class library and so doesn't have access to the usual properties of controllers and views.

I'm porting an app from ASP.Net to ASP.Net Core and this library is being called from lots of places and passing parameters through from the controller is not something that I want to be doing - it would be hours of work due to number of places I would have to pass everything through.

I'm using ASP.Net Core 2.1, running on .Net Framework 4.7.1 (although I plan to port to .Net Core in a future release, once some dependencies have been removed so I want a solution that will work with Famework and .Net Core)

like image 855
Mog0 Avatar asked Sep 13 '25 02:09

Mog0


2 Answers

You can use HttpRequest.PathBase:

string relativeUrl = "~/foo";
string absoluteUrl = httpContext.Request.PathBase + relative[1..];
like image 69
Mr. TA Avatar answered Sep 15 '25 16:09

Mr. TA


For those who do not yet have an available HttpRequest object instance, for instance during application startup, there is now a NuGet package called Microsoft.AspNetCore.SystemWebAdapters that provides the features of VirtualPathUtility from System.Web to an ASP.NET Core application.

https://github.com/dotnet/systemweb-adapters

like image 24
Johan van Tonder Avatar answered Sep 15 '25 16:09

Johan van Tonder