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

Benjamin Pollack picture Benjamin Pollack · Aug 17, 2009 · Viewed 313.8k times · Source

How can I quickly determine what the root URL is for my ASP.NET MVC application? I.e., if IIS is set to serve my application at http://example.com/foo/bar, then I'd like to be able to get that URL in a reliable way that doesn't involve getting the current URL from the request and chopping it up in some fragile way that breaks if I re-route my action.

The reason that I need the base URL is that this web application calls another one that needs the root to the caller web application for callback purposes.

Answer

tghw picture tghw · Aug 17, 2009

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