I wrote a blog post called How to build absolute action URLs using the UrlHelper class in which I present a custom extension method named AbsoluteAction
. I encourage you to check it out!
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
ASP.NET MVC includes built-in functionality for the generation of absolute URLs, though not in a very intuitive way.
There are several overloads of UrlHelper.Action()
method that enable you to pass additional parameters like route values, the protocol to use and the host name for the URL. If you are using any overload that allows you to specify the protocol
parameter, the generated URL will be absolute. Thus, the following code can be used to generate an absolute URL for the About action method of the HomeController:
@Url.Action("About", "Home", null, "http")