Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get IUrlHelper from inside Html helper

Tags:

asp.net-core

I need the url helper inside an html Helper so I have

IHtmlHelper<T> html and need to get IUrlHelper

I tried this:

html.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelper));

but it returns null

like image 602
Omu Avatar asked Feb 06 '23 13:02

Omu


1 Answers

got the answer here: https://github.com/aspnet/Mvc/issues/5051 so it looks like this:

public static IHtmlContent MyHelper(this IHtmlHelper<T> html){
    var urlHelperFactory = (IUrlHelperFactory)html.ViewContext.HttpContext.RequestServices.GetService(typeof(IUrlHelperFactory));            
    var urlHelper = urlHelperFactory.GetUrlHelper(aweInfo.Html.ViewContext);
like image 111
Omu Avatar answered Feb 19 '23 05:02

Omu