Search code examples
c#dependency-injectionasp.net-core-mvcmiddlewareasp.net-core-mvc-2.0

Get UrlHelper in middleware with ASP.NET Core MVC 2.0


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?}");
    });
}

Solution

  • 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.