If you can use the Controller / Action Names...
You should use the Url.Action()
method for this.
Typically, Url.Action()
will return something similar to what you presently expect when provided with just the Controller and Action names :
// This would yield "Controller/Action"
Url.Action("Action","Controller");
However, when you pass in the protocol parameter (i.e. http
, https
etc.) then the method will actually return a complete, absolute URL. For the sake of convienence, you can use the Request.Url.Scheme
property to access the appropriate protocol as seen below :
// This would yield "http://your-site.com/Controller/Action"
Url.Action("Action", "Controller", null, Request.Url.Scheme);
You can see an example of this in action here.
If you only have a relative URL string...
If you only have access to something like a relative URL (i.e. ~/controller/action
), then you may want to create a function that will extend the current functionality of the Url.Content()
method to support serving absolute URLs :
public static class UrlExtensions
{
public static string AbsoluteContent(this UrlHelper urlHelper, string contentPath)
{
// Build a URI for the requested path
var url = new Uri(HttpContext.Current.Request.Url, urlHelper.Content(contentPath));
// Return the absolute UrI
return url.AbsoluteUri;
}
}
If defined properly, this would allow you to simply replace your Url.Content()
calls with Url.AbsoluteContent()
as seen below :
Url.AbsoluteContent("~/Controller/Action")
You can see an example of this approach here.