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

本文关键字:helper html 上下文 获取 urlHel 静态方法 net core mvc asp | 更新日期: 2023-09-27 18:01:32

我在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.

张贴在这个stackoverflow答案的解决方案是注入IUrlHelperFactory,但是我使用静态html helper方法,我在我的cshtml调用,而不是在标签helper中使用的类。

我如何改变我的代码工作在ASP.net Core

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

微软可能在。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);
            //...
        }
    }
}

将原始代码更改为:

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