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

6
我该如何在中间件中获取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?}");
    });
}
2个回答

5

您的应用程序中有2个管道。一个是您要链接的ASP.NET Core管道。另一个是通过UseMvc设置的ASP.NET MVC管道。ActionContext是一个MVC概念,这就是为什么在ASP.NET Core管道中不可用的原因。要钩入MVC管道,可以使用过滤器


谢谢Hans,现在我可以在全局范围内添加过滤器了。 - KevinBui

-1

您可以尝试将其添加到ConfigureServices(IServiceCollection services)中的服务容器中。您可以按照以下方式执行此操作:

 public IServiceProvider ConfigureServices(IServiceCollection services) {
    //Service injection and setup
    services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
                services.AddScoped<IUrlHelper>(factory =>
                {
                    var actionContext = factory.GetService<IActionContextAccessor>()
                                               .ActionContext;
                    return new UrlHelper(actionContext);
                });

    //....

   // Build the intermediate service provider then return it
    return services.BuildServiceProvider();
}

然后,您可以修改Configure()方法以接收IServiceProvider,然后通过以下方式获取UrlHelper的实例。

public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider) {

    //Code removed for brevity

    var urlHelper = serviceProvider.GetService<IUrlHelper>(); <-- helper instance

    app.UseMvc();
}

注意:请在services.Mvc()之后添加此代码。


那么,在中间件中如何获取UrlHelper?在添加了“services.AddScoped<IUrlHelper>(...)”之后,我不知道该如何使用它。 - KevinBui
actionContextAccessor.ActionContext still return null, exception throw at line return new UrlHelper(actionContext); - KevinBui

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接