我在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
中使用?
答案 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);
//...
}
}
}