【问题标题】:Using LinkGenerator outside of Controller在控制器之外使用 LinkGenerator
【发布时间】:2019-06-15 09:37:45
【问题描述】:

在 ASP.NET Core 2.2 控制器上,我有以下内容:

var url = _linkGenerator.GetUriByAction(HttpContext, action: "GetContentByFileId", values: new { FileId = 1 });

我在Controller中注入了LinkGenerator ...

现在我需要在一个不是控制器的类中生成 url,所以我尝试了:

var url = _linkGenerator.GetUriByAction(action: "GetContentByFileId", controller: "FileController", values: new { FileId = 1 });

但是,我收到消息说我需要更多参数。为什么?

在控制器之外使用 LinkGenerator 的正确方法是什么?

【问题讨论】:

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


    【解决方案1】:

    如果不使用需要HttpContextGetUriByAction 重载,那么您必须提供所有其他所需的参数

    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

    作为替代方案,您也可以考虑注入IHttpContextAccessor,这样您就可以在控制器外部访问HttpContext,并且能够像从控制器内部调用时一样进行调用。

    var url = _linkGenerator.GetUriByAction(_accessor.HttpContext, 
        action: "GetContentByFileId", 
        values: new { FileId = 1 }
    );
    

    【讨论】:

    • 链接已损坏:/
    • @zola25 更新了源代码移动到的链接。
    • @zola25 感谢您对损坏的链接的提醒。
    • 谢谢。 MS Blazor 团队刚刚告诉我,我应该使用 LinkGenerator,因为 Blazor 中没有 HttpContext,我正试图解决这个问题。
    【解决方案2】:

    我使用这个解决方案,它对我来说很好。

    首先:创建包含 IHttpContextAccessor 作为构造函数参数的自定义类服务。 通过IHttpContextAccessor可以获得LinkGenerator服务。

    public class MyCustomClassService
    {
        LinkGenerator _LinkGenerator;
        public MyCustomClassService(IHttpContextAccessor haccess)
        {
            _LinkGenerator = haccess.HttpContext.RequestServices.GetRequiredService<LinkGenerator>();
        }
    
        public LinkGenerator LinkGenerator
        {
            get
            {
                return _LinkGenerator;
            }
        }
    
    }
    

    那么:你需要将 MyCustomClassService 注册到 Startup 类中。

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<MyCustomClassService>();
        }
    }
    

    【讨论】:

    • 为什么你更喜欢这种方法而不是接受的答案?
    • 只是想提出一个具有更多实施细节的解决方案以进行更多说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-06
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多