Generating links with UrlHelper outside of ASP.NET Core

UrlHelper outside of ASP.NET CoreI’ve been trying to solve the issue of generating links with UrlHelper outside of ASP.NET Core.  The problem I was facing was wanting to use UrlHelper while not directly in the context of ASP.NET Core.

There are two specific scenarios were:

  • Generate a link for an ASP.NET Core MVC route that I was going to be using in an email.  This is a separate process that is not running ASP.NET Core but does have references to the assemblies that contain the controllers.
  • Generate a link for an ASP.NET Core MVC route from a Nancy Module running in a Katana self host.  This also has a reference to the assemblies containing the asp.net controllers.

UrlHelper

I tried various different solutions but couldn’t come up with a solution.  After a ton of searching, I finally found a StackOverflow post that provided a solution.  Although not pretty, it does work.

Here’s a sample console application.  First, there are a few extension methods for setting up the web host builder, application builder and generating the UrlHelper with a default HttpContext.

Next is to create a Startup class we will use in our web host builder.

Lastly, putting it all into place is to build a web host and then use the extension method to get a UrlHelper.  You’ll notice you need to provide the base path to the extension method.  This is because the extension method uses this base address as the request within the HttpContext it’s creating.

Source

I’ve created a console application with the source available on GitHub.

If you know of a method of generating a link to an ASP.NET Core MVC route without being in the context of ASP.NET Core, please let me know on Twitter or in the comments.

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.