Reputation: 1377
Really simple I hope. I just want to do the equivalent of
Url.Action("SomeAction", "SomeController", new { id = 3 });
But inside a service class. Not inside a controller class or IActionResult method
In a plain old service class. Because of the service call having all the data I don't want to pass in other information so my service call is nice and clean.
I've come close but nothing seems to work, either that or it cant be done.
I tried to dependency inject this
services.AddScoped<IUrlHelper>(x => x
.GetRequiredService<IUrlHelperFactory>()
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));
In my service call I used (DI) this
public AdminService(..., IUrlHelper urlHelper)
so in my service method I could to this
string editUrl = _urlHelper.Action("EditRole", "Admin", new { id = 0 });
which got rid of all the red squiglies but at run time this bit caused me a problem
.GetUrlHelper(x.GetRequiredService<IActionContextAccessor>().ActionContext));
Upvotes: 0
Views: 639
Reputation: 1377
@SMM I had to add this to my startup but otherwise, works, so thank you
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IUrlHelper, UrlHelper>();
Upvotes: 0
Reputation: 37
You can inject IUrlHelper interface inside a service class.
public class ServiceClass
{
private readonly IActionContextAccessor _actionContextAccessor;
private readonly IUrlHelperFactory _urlHelperFactory;
public ServiceClass(IActionContextAccessor actionContextAccessor,
IUrlHelperFactory urlHelperFactory,)
{
_actionContextAccessor = actionContextAccessor;
_urlHelperFactory = urlHelperFactory;
}
public string CreateUrl()
{
var urlHelper = _urlHelperFactory.GetUrlHelper(_actionContextAccessor.ActionContext);
string url = urlHelper.Action("SomeAction", "SomeController");
return url;
}
}
Upvotes: 4
Reputation: 1
Url.Action generates only an url. @Url.Action("actionName", "controllerName", new { id = id })
Html.ActionLink generates an tag automatically.
Upvotes: -2