March 19, 2019

Customising URL generation in ASP.NET Core MVC

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 hostname parameter.

To override the hostname only:

hostname: mydomain.com

To override the hostname and port:

hostname: mydomain.com:5000

To override the hostname, port and path:

hostname: mydomain.com/my/path

This took me a while to figure out so I hope this blog post saves you some time.

© 2022 Ben Foster