如何从asp.net core mvc html helper静态方法中的html helper上下文中获取urlHelper

dfm*_*tro 3 c# asp.net-core-mvc asp.net-core

我有一个项目ASP.NET 5 RC1,我曾经在我的 HTMLHelper 静态方法中从 HtmlHelper 上下文中获取 urlHelper

    public static IHtmlContent MyHtmlHelperMethod<TModel, TResult>(
            this IHtmlHelper<TModel> htmlHelper,
            Expression<Func<TModel, TResult>> expression)
    {



       //get the context from the htmlhelper and use it to get the urlHelper as it isn't passed to the method from the view
        var urlHelper = GetContext(htmlHelper).RequestServices.GetRequiredService<IUrlHelper>();

        var controller = htmlHelper.ViewContext.RouteData.Values["controller"].ToString();
        string myLink;
        if (htmlHelper.ViewContext.RouteData.Values["area"] == null)
        {
            myLink= urlHelper.Action("index", controller);

        } else
        {

            string area = htmlHelper.ViewContext.RouteData.Values["area"].ToString();
            myLink = urlHelper.Action("index", controller, new { area = area });

        }  
        string output = "<div><a href = \"" + myLink + "\" class=\"myclass\"><blabla></blabla>My Link</a></div>;
        return new HtmlString(output.ToString());
    }
Run Code Online (Sandbox Code Playgroud)

但是,ASP.NET Core它不再起作用,并且出现运行时错误

>InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' has been registered.
Run Code Online (Sandbox Code Playgroud)

这个stackoverflow 答案中发布的解决方案是注入IUrlHelperFactory,但是我使用的是我在我的cshtml而不是标签助手中使用的类中调用的静态 html 帮助程序方法。

如何更改我的代码以使其工作ASP.net Core

dev*_*ric 5

将您的原始代码更改为:

var urlHelperFactory = GetContext(htmlHelper).RequestServices.GetRequiredService<IUrlHelperFactory>();
var actionContext = GetContext(htmlHelper).RequestServices.GetRequiredService<IActionContextAccessor>().ActionContext;
var urlHelper = urlHelperFactory.GetUrlHelper(actionContext); 
Run Code Online (Sandbox Code Playgroud)


Dir*_*k R 5

微软可能在 .net core 2.1 中做了一些改动。它比接受的答案稍微简单。我希望这对某人有帮助。

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.Extensions.DependencyInjection;

namespace MyApp.Extensions
{
    public static class WebApiHelperExtension
    {
        public static IHtmlContent WebApiUrl(this IHtmlHelper htmlHelper)
        {
            var urlHelperFactory = htmlHelper.ViewContext.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>();
            var urlHelper = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext);
            //...
        }
    }
}
Run Code Online (Sandbox Code Playgroud)