【发布时间】:2020-09-30 13:38:49
【问题描述】:
我在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 中使用的类。
如何更改我的代码以在 ASP.net Core 中工作?
【问题讨论】:
标签: c# asp.net-core asp.net-core-mvc