Getting Absolute URL from an ASP.NET MVC Action
From within the controller:
var path = VirtualPathUtility.ToAbsolute(pathFromPoco);
var url = new Uri(Request.Url, path).AbsoluteUri
You can do it by the following:
var urlBuilder =
new System.UriBuilder(Request.Url.AbsoluteUri)
{
Path = Url.Action("Action", "Controller"),
Query = null,
};
Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
// or urlBuilder.Uri.ToString()
Instead of Url.Action()
in this sample, you can also use Url.Content()
, or any routing method, or really just pass a path.
But if the URL does go to a Controller
Action
, there is a more compact way:
var contactUsUriString =
Url.Action("Contact-Us", "About",
routeValues: null /* specify if needed */,
protocol: Request.Url.Scheme /* This is the trick */);
The trick here is that once you specify the protocol
/scheme when calling any routing method, you get an absolute URL. I recommend this one when possible, but you also have the more generic way in the first example in case you need it.
I have blogged about it in details here:
http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/
Extracted from Meligy’s AngularJS & Web Dev Goodies Newsletter