I'm currently trying to do something that was dead simple and straight forward in ASP.NET 4 however this ins't the case now in ASP.NET 5.
Previously to use the UrlHelper it was dead simple:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
However I can't for the life of me wrap my head around how to use the new UrlHelper. I'm looking at the test cases and either I'm completely daft or I'm missing something and I can't seem to figure it out. Any help here in clearing up this would be great.
Update - Post RC2
As @deebo mentioned, you no longer can get an
IUrlHelperdirectly from DI. Instead you need to inject anIUrlHelperFactoryand anIActionContextAccessorinto your class and use them to get theIUrlHelperinstance as in:You need to also register the in your startup class (
IUrlHelperFactoryis already registered by default):Bear in mind this will only work as long as the code where you get the actionContext is running after the MVC/routing middleware! (Otherwise
actionAccessor.ActionContextwould be null)I have retrieved the
IUrlHelperusing theIServiceProviderinHttpContext.RequestServices.Usually you will have an
HttpContextproperty at hand:In a controller action method you can do:
In a filter you can do:
Another option would be taking advantage of the built-in dependency injection, for example your controller could have a constructor like the following one and at runtime an
IUrlHelperinstance will be provided: