在 ASP.NET Core 2.2 Controller 上,我有以下内容:
var url = _linkGenerator.GetUriByAction(HttpContext, action: "GetContentByFileId", values: new { FileId = 1 });
我在 Controller 中注入(inject)了 LinkGenerator ...
现在我需要在一个不是 Controller 的类中生成 url,所以我尝试了:
var url = _linkGenerator.GetUriByAction(action: "GetContentByFileId", controller: "FileController", values: new { FileId = 1 });
但是,我收到消息说我需要更多参数。为什么?
在 Controller 之外使用 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)
在您的示例中,这将是 scheme
和 host
。
作为替代方案,您还可以考虑注入(inject) IHttpContextAccessor
,这样您就可以在 Controller 外部访问 HttpContext
,并且能够像从在 Controller 内。
var url = _linkGenerator.GetUriByAction(_accessor.HttpContext,
action: "GetContentByFileId",
values: new { FileId = 1 }
);
关于c# - 在 Controller 之外使用 LinkGenerator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54299423/