When generating route or action URLs in ASP.NET Core MVC, the scheme, hostname and port will default to that of the current request. For instance, if my application is running at http://localhost:5000 and I generate a route URL, the resulting value will be http://localhost:5000/my-route-pattern.
In some cases we need to override other parts of the URL, such as the host and port.
This can be achieved by using an overload of
IUrlHelper that accepts these additional parameters:
public static string RouteUrl(this IUrlHelper helper, string routeName, object values, string protocol);
What isn’t covered in the documentation is how to also override the port and path of the generated URL. This is possible using the correct format of the
To override the hostname only:
To override the hostname and port:
To override the hostname, port and path:
This took me a while to figure out so I hope this blog post saves you some time.