On an ASP.NET Core 2.2 controller I have the following:
var url = _linkGenerator.GetUriByAction(HttpContext, action: "GetContentByFileId", values: new { FileId = 1 });
I injected LinkGenerator in the Controller ...
Now I need generate the url in a class which is not a controller so I tried:
var url = _linkGenerator.GetUriByAction(action: "GetContentByFileId", controller: "FileController", values: new { FileId = 1 });
However, I get the message saying I need more arguments. Why?
What is the correct way to use LinkGenerator outside of a Controller?
If not using the GetUriByAction
overload that requires HttpContext
then you have to provide all the required arguments of the other
public static string GetUriByAction(
this LinkGenerator generator,
string action,
string controller,
object values,
string scheme,
HostString host,
PathString pathBase = default,
FragmentString fragment = default,
LinkOptions options = default)
Source
Which in your example would be the scheme
and host
.
As an alternative you can also consider injecting IHttpContextAccessor
so you have access to HttpContext
outside of controller and be able to make the call just like how you did when invoked from within the controller.
var url = _linkGenerator.GetUriByAction(_accessor.HttpContext,
action: "GetContentByFileId",
values: new { FileId = 1 }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With