IUrlHelper未在RC2中解析

时间:2016-05-19 09:17:04

标签: asp.net-core .net-core-rc2

从ASP.NET Core RC1迁移到RC2时,我的TagHelper无法解析注入的IUrlHelpers。

[HtmlTargetElement("usermenulink", Attributes = "controller-name, action-name, menu-text, menu-item, active-item")]

public class UserMenuItemTagHelper : TagHelper
{
    public IUrlHelper _UrlHelper { get; set; }

    public UserMenuItemTagHelper(IUrlHelper urlHelper)
    {
        _UrlHelper = urlHelper;
    }
    //... abbreviated
}

相反,我得到了一个例外:

处理请求时发生未处理的异常。

  InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' while attempting to activate '...TagHelpers.UserMenuItemTagHelper'.

有什么想法吗?

1 个答案:

答案 0 :(得分:13)

我发现自己,使用RC2,您必须(或可以)注入IUrlHelperFactory并获取此的UrlHelper实例。

public class UserMenuLinkTagHelper : TagHelper
{
    [ViewContext]
    public ViewContext ViewContext { get; set; }

    public IUrlHelperFactory _urlHelperFactory { get; set; }

    public UserMenuLinkTagHelper(IUrlHelperFactory urlHelperFactory)
    {
        _urlHelperFactory = urlHelperFactory;
    }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var urlHelper = _urlHelperFactory.GetUrlHelper(ViewContext);

        string menuUrl = urlHelper.Action(ActionName, ControllerName);

        //...
    }


}

以下是Mvc团队当前实施的示例: https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/ImageTagHelper.cs