Generating links inside a .NET Core Tag Helper

Previously when generating links inside any non view code I'd always try and get hold of an instance of IUrlHelper, but I've found a simpler way that has been available since .NET Core 2.2.

LinkGenerator can be injected into a tag helper or any class. It has all the useful methods of IUrlHelper, with fewer dependencies. It only asks for HttpContext if it absolutely needs it, which in many cases it does not.

Inject it into your class like so:

private readonly LinkGenerator _linkGenerator;

public NogginTagHelper(LinkGenerator linkGenerator)
{
    _linkGenerator = linkGenerator;
}

Using the following namespace:

using Microsoft.AspNetCore.Routing;

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

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

    base.Process(context, output);
}

And that's all there is to it. No need to set anything beforehand. It just works.

No Comments