• 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 …

  • 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. …