Zabavsky
Zabavsky

Reputation: 13640

ASP.NET MVC 6 application's virtual application root path

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

Upvotes: 3

Views: 5414

Answers (2)

Shadi Alnamrouti
Shadi Alnamrouti

Reputation: 13278

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.

Upvotes: 2

Daniel J.G.
Daniel J.G.

Reputation: 34992

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;
}

Upvotes: 7

Related Questions