Reputation: 1323
Whilst attempting to generate urls from outside of my controller , I'm unable to get at Request.Scheme
.
In the controller i can do this to generate a url without problems:
//get UserManager bits
var callBackUrl = Url.CallBackExtensionLink(user.Id, token, Request.Scheme);
CallBackExtensionLink()
is an IUrlHelper
extension method that i created.
However,Request.Scheme throws a null reference exception.
How can I get the value outside of the controller ?
Upvotes: 0
Views: 737
Reputation: 1323
So after some more investigating I was able to mitigate this problem by injecting IUrlHelper
into the DI in .net core which is done differently to how others are done.
add this to the DI :
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddScoped<IUrlHelper>(x => {
var actionContext = x.GetRequiredService<IActionContextAccessor>().ActionContext;
var factory = x.GetRequiredService<IUrlHelperFactory>();
return factory.GetUrlHelper(actionContext);
});
And then pass IUrlHelper into the implementing class constructor.
private readonly IUrlHelper helper;
YourConstructor(IUrlHelper helper){
this.helper = helper;
}
Upvotes: 1