Roberto Correia Roberto Correia - 1 month ago 29
C# Question

Injection of HtmlHelper on a TagHelper class and dynamic url generation

I'm making a TagHelper that must generate a list of links (in this example, the TagHelper generate a single link to make things clear).
Every link must call a controller, a action, and pass a parameter according with results from a API call.

Controller:

public class ContentController : Controller
{
public async Task<IActionResult> DoSomething(string typeOfContent)
{
...
}
}


TagHelper:

public class ContentTypeTagHelper : TagHelper
{
public ContentTypeTagHelper(IUrlHelper urlHelper)
{
_urlHelper = urlHelper;
}

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = null;
output.TagMode = TagMode.SelfClosing;

string contentType = SomeApiCall.GetContentTypes();

// this is the correct way to do this?
var url = _urlHelper.Action("DoSomething", "ContentController", new {typeOfContent = contentType});
}
}


and in Startup.cs, I included the following code:
services.AddSingleton<IHtmlHelper, HtmlHelper>();


If I try to run this code, I receive a error.
InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate 'Foo.TagHelpers.ContentTypeTagHelper'

Answer

IHtmlHelper is not the same as IUrlHelper. Actually what you need to have injected is IUrlHelperFactory and IActionContextAccessor which you can then use to create an UrlHelper.

You can see an example here in my PagerTagHelper