如何在中间件中获取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?}");
});
}
答案 0 :(得分:3)
您的应用中有2个管道。您正在连接的ASP.NET核心管道。以及由UseMvc设置的ASP.NET MVC管道。 ActionContext是一个MVC概念,这就是它在ASP.NET核心管道中不可用的原因。要挂钩MVC管道,您可以使用过滤器:https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters
编辑:修正了文章的链接
答案 1 :(得分:-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()