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.
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.
Maybe it is extension or modification of the answers posted here but I use simply the following line and it works:
When my path is:
http://host/iis_foldername/controller/action
then I receive :
http://host/iis_foldername/
For ASP.NET MVC 4 it is a bit different:
This is working in ASP .NET MVC 4 In any controller action you can write: 1stline gets the whole url+Query String. 2nd line remove local path & query ,last '/' symbol. 3rd line add '/' symbol at last position.
For url with aplication alias like http://example.com/appAlias/... You can try this:
The following snippet works nicely for me in MVC4, and doesn't need an
HttpContext
available: