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

时间:2016-08-10 05:47:35

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

我在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());
    }

然而在ASP.NET Core它不再有效,我得到运行时错误

>InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' has been registered.

this stackoverflow回答中发布的解决方案是注入IUrlHelperFactory,但是我使用的是我在cshtml中调用的静态html辅助方法,而不是在taghelpers中使用的类。< / p>

如何更改我的代码才能在ASP.net Core中使用?

2 个答案:

答案 0 :(得分:4)

将原始代码更改为:

var urlHelperFactory = GetContext(htmlHelper).RequestServices.GetRequiredService<IUrlHelperFactory>();
var actionContext = GetContext(htmlHelper).RequestServices.GetRequiredService<IActionContextAccessor>().ActionContext;
var urlHelper = urlHelperFactory.GetUrlHelper(actionContext); 

答案 1 :(得分:1)

Microsoft可能已经在.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);
            //...
        }
    }
}