19

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)

Mog0
  • 1,689
  • 1
  • 16
  • 40
  • 2
    This question is not a duplicate, b/c it's not about getting "absolute URLs" despite what the method name is, this method is used to resolved tilda-paths. – Alex from Jitbit Aug 24 '21 at 18:19

1 Answers1

2

You can use HttpRequest.PathBase:

string relativeUrl = "~/foo";
string absoluteUrl = httpContext.Request.PathBase + relative[1..];
Mr. TA
  • 5,230
  • 1
  • 28
  • 35
  • @MrTA :: How about during startup, if you are using in-process IIS integration? You haven't had a request yet, so you can't rely on what the end-user sent you... – jimbobmcgee Jul 14 '22 at 21:21
  • @jimbobmcgee good question, I'm not sure. With IIS, you can read the metabase and figure out the virtual path that way, but that does seem to be complicated. – Mr. TA Jul 15 '22 at 23:35