How can I get my webapp's base URL in ASP.NET MVC?

Assuming you have a Request object available, you can use:

string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));

If it's not available, you can get to it via the context:

var request = HttpContext.Current.Request

So none of the ones listed here worked for me, but using a few of the answers, I got something working:

public string GetBaseUrl()
{
    var request = HttpContext.Current.Request;
    var appUrl = HttpRuntime.AppDomainAppVirtualPath;

    if (appUrl != "/") 
        appUrl = "/" + appUrl;

    var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

    return baseUrl;
}

Update for ASP.NET Core / MVC 6:

ASP.NET Core makes this process a bit more painful, especially if you are deep in your code. You have 2 options to get at the HttpContext

1) Pass it in from your controller:

var model = new MyClass(HttpContext);

then in model:

private HttpContext currentContext;

public MyClass(HttpContext currentContext)
{
    this.currentContext = currentContext;
}

2) Perhaps the cleaner way is to inject it into your class, which starts with registering the types in your Startup:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddTransient<MyClass, MyClass>();
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}

then have it injected for you like this:

private HttpContext currentContext;

public MyClass(IHttpContextAccessor httpContextAccessor)
{
    currentContext = httpContextAccessor.HttpContext;
}

in either case, here is the updated for .NET Core GetBaseUrl():

public string GetBaseUrl()
{
    var request = currentContext.Request;

    var host = request.Host.ToUriComponent();

    var pathBase = request.PathBase.ToUriComponent();

    return $"{request.Scheme}://{host}{pathBase}";
}

In Code:

Url.Content("~/");

MVC3 Razor Syntax:

@Url.Content("~/")

Maybe it is extension or modification of the answers posted here but I use simply the following line and it works:

Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~")

When my path is: http://host/iis_foldername/controller/action
then I receive : http://host/iis_foldername/


The following snippet works nicely for me in MVC4, and doesn't need an HttpContext available:

System.Web.HttpRuntime.AppDomainAppVirtualPath