Mig*_*ura 5 c# asp.net-core asp.net-core-2.2
在 ASP.NET Core 2.2 控制器上,我有以下内容:
var url = _linkGenerator.GetUriByAction(HttpContext, action: "GetContentByFileId", values: new { FileId = 1 });
Run Code Online (Sandbox Code Playgroud)
我在控制器中注入了 LinkGenerator ...
现在我需要在一个不是控制器的类中生成 url,所以我尝试了:
var url = _linkGenerator.GetUriByAction(action: "GetContentByFileId", controller: "FileController", values: new { FileId = 1 });
Run Code Online (Sandbox Code Playgroud)
但是,我收到消息说我需要更多参数。为什么?
在控制器之外使用 LinkGenerator 的正确方法是什么?
如果不使用GetUriByAction需要的重载,HttpContext那么您必须提供另一个所需的所有参数
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)
Run Code Online (Sandbox Code Playgroud)
在您的示例中将是schemeand host。
作为替代方案,您还可以考虑注入,IHttpContextAccessor以便您可以访问HttpContext控制器外部,并能够像从控制器内部调用时那样进行调用。
var url = _linkGenerator.GetUriByAction(_accessor.HttpContext,
action: "GetContentByFileId",
values: new { FileId = 1 }
);
Run Code Online (Sandbox Code Playgroud)