Using URL helper inside your .NET Core Tag Helper

I've discovered a better way of doing this. Check out my new post on using LinkGenerator instead.

If you're writing a tag helper and would like to generate links using IUrlHelper then you can not inject this directly. You need to inject an IUrlHelperFactory and then there are a few hoops that you need to jump through.

This is how to set up the UrlHelper inside you tag helper constructor:

private readonly IUrlHelper _urlHelper;

public NogginTagHelper(IUrlHelperFactory urlHelperFactory, IActionContextAccessor contextAccessor)
{
    _urlHelper = urlHelperFactory.GetUrlHelper(contextAccessor.ActionContext);
}

You'll need to use these namespaces:

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Routing;

You can then use the _urlHelper in your tag helper's process method like this:

public override void Process(TagHelperContext context, TagHelperOutput output)
{
    var src = _urlHelper.Action("NogginAction", "NogginController");
    output.Attributes.SetAttribute("src", src);

    base.Process(context, output);
}

IActionContextAccessor is required by IUrlHelperFactory, but it is registered with IoC as standard. So you need to register it in ConfigureServices in startup like this:

services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

I'm using this in my latest .NET 5 MVC app, but it should work from .NET Core 2.0 upwards.