在中间件ASP.NET MVC Core 2.0中获取UrlHelper [英] Get UrlHelper in middleware asp.net mvc core 2.0

查看:223
本文介绍了在中间件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

固定至文章的链接

这篇关于在中间件ASP.NET MVC Core 2.0中获取UrlHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆