I have a project in ASP.NET 5 RC1
which I used to get the the urlHelper from the HtmlHelper Context in my HTMLHelper static methods
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());
}
However in ASP.NET Core
it no longer works and I get the runtime error
>InvalidOperationException: No service for type 'Microsoft.AspNetCore.Mvc.IUrlHelper' has been registered.
The solution posted in this stackoverflow answer is to inject IUrlHelperFactory
, however I am using static html helper methods I call in my cshtml
and not classes which is used in taghelpers.
How do I change my code to work in ASP.net Core
?