3

How do I get the virtual root path of the application on the server?

In another words: how can I do the following in ASP.NET MVC 6?

HttpContext.Current.Request.ApplicationPath

Zabavsky
  • 13,340
  • 8
  • 54
  • 79
  • http://stackoverflow.com/questions/35082888/asp-net-mvc-6-applications-virtual-application-root-path – dfmetro Jan 29 '16 at 13:18
  • Check out [this question](http://stackoverflow.com/questions/32631066/how-to-consistently-get-application-base-path-for-asp-net-5-dnx-project-on-both) – Daniel J.G. Jan 29 '16 at 15:01
  • @DanielJ.G., I did, it provides you with an absolute path to project's folder which is not what I need. – Zabavsky Jan 30 '16 at 09:16
  • Can you not just use `@Url.Content("~/")`? I also just had a look at [the source code](https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Routing/UrlHelper.cs) and it is resolving "~" to the application path using `HttpContext.Request.PathBase` – Daniel J.G. Feb 01 '16 at 10:33
  • @DanielJ.G., yes, I think you're right, though I can't find anywhere proper specification of the `PathBase` property. Please post your answer. – Zabavsky Feb 01 '16 at 19:55

2 Answers2

7

What you need can be achieved with @Url.Content("~/"), which will map "~" to your virtual application root path.

Having a look at the source code, it seems to do so using the HttpContext.Request.PathBase property:

public virtual string Content(string contentPath)
{
    if (string.IsNullOrEmpty(contentPath))
    {
        return null;
    }
    else if (contentPath[0] == '~')
    {
        var segment = new PathString(contentPath.Substring(1));
        var applicationPath = HttpContext.Request.PathBase;

        return applicationPath.Add(segment).Value;
    }

    return contentPath;
}
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112
2

I use the following in MVC Core RC2:

Instead of "~/something" I use

Context.Request.PathBase + "/something"

or even more simply, just use "/something", which means starting a path with a slash tells asp core to start from the root.

Shadi Alnamrouti
  • 11,796
  • 4
  • 56
  • 54