Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LinkGenerator outside of Controller

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?

like image 987
Miguel Moura Avatar asked Jan 21 '19 23:01

Miguel Moura


1 Answers

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 }
);
like image 146
Nkosi Avatar answered Sep 30 '22 02:09

Nkosi