c# - 在 Controller 之外使用 LinkGenerator

标签 c# asp.net-core asp.net-core-2.2

在 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)

Source

在您的示例中,这将是 schemehost

作为替代方案,您还可以考虑注入(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/

相关文章:

c# - WCF 服务中跨 session 持续存在的静态变量

c# - 如何允许访问 MVC 中的方法?

c# - 大型 float 列表的查找函数 - 内存计算?

c# - .net framework 上的 startup 和 startup.auth 代码放在哪里(不是 .net core)

c# - 独立的 ASP.Net Core 不读取 appsettings.json 文件

iis - ASP.NET Core 2.2(发布版)产生错误并停止 w3wp

c# - 如何使用 jQuery 禁用按钮,但在单击按钮后运行服务器代码?

ASP.NET Core 中使用 IActionResult 的 C# 接口(interface)概念说明

c# - 将 asp.net core 独立 Web 应用程序部署到 Ubuntu。 appsettings.json 中存在的数据库名称为空

c# - 如何在 asp net core 2.2 中间件中多次读取请求正文?