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