使用 ASP.NET Core MVC 2.0 在中间件中获取 UrlHelper

Kev*_*Bui 6 c# dependency-injection middleware asp.net-core-mvc asp.net-core-mvc-2.0

如何在中间件中获取UrlHelper。我尝试如下但actionContextAccessor.ActionContext返回 null。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSession();

    services
        .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie();

    services.AddMvc();
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseSession();

    if (env.IsDevelopment())
    {
        app.UseBrowserLink();
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseAuthentication();
    app.Use(async (context, next) =>
    {
        var urlHelperFactory = context.RequestServices.GetService<IUrlHelperFactory>();
        var actionContextAccessor = context.RequestServices.GetService<IActionContextAccessor>();

        var urlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
        await next();
        // Do logging or other work that doesn't write to the Response.
    });

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
Run Code Online (Sandbox Code Playgroud)

Han*_*ian 6

您的应用程序中有 2 个管道。您正在连接的 ASP.NET Core 管道。以及由 UseMvc 设置的 ASP.NET MVC 管道。ActionContext 是一个 MVC 概念,这就是它在 ASP.NET Core 管道中不可用的原因。要挂钩 MVC 管道,您可以使用Filters