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

问题描述:

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

How can I get UrlHelper in middleware. I try as below but actionContextAccessor.ActionContext return 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?}");
    });
}

您的应用中有2个管道.您所迷恋的ASP.NET核心管道.以及由UseMvc设置的ASP.NET MVC管道. ActionContext是MVC概念,这就是为什么它在ASP.NET核心管道中不可用的原因.要加入MVC管道,可以使用过滤器: https: //docs.microsoft.com/zh-CN/aspnet/core/mvc/controllers/filters

There are 2 pipelines in your app. The ASP.NET core pipeline that you're hooking into. And the ASP.NET MVC pipeline which is set up by UseMvc. ActionContext is an MVC concept and that's why it's not available in the ASP.NET core pipeline. To hook into the MVC pipeline, you can use Filters: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters

固定至文章的链接