views:

1292

answers:

3

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.

A: 

You could have a static method that looks at HttpContext.Current and decides which URL to use (development or live server) depending on the host ID. HttpContext might even offer some easier way to do it, but this is the first option I found and it works fine.

Adrian Grigore
+6  A: 

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

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

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

var request = HttpContext.Current.Request
tghw
I tried this, but neither HttpContext.Current.Request.Authority, nor HttpContext.Current.Request.Scheme was defined.
Adrian Grigore
Sorry, forgot the .Url part, fixed
tghw
What is `urlHelper.Content("~")`? How do I create define `urlHelper`? Thanks!
Maxim Zaslavsky
A: 

The trick with relying upon IIS is that IIS bindings can be different from your public URLs (WCF I'm looking at you), especially with multi-homed production machines. I tend to vector toward using configuration to explicitly define the "base" url for external purposes as that tends to be a bit more successful than extracting it from the Request object.

Wyatt Barnett