问题
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?}");
});
}
回答1:
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
Edit: Fixed link to article
回答2:
You can try adding it to the service container on the ConfigureServices(IServiceCollection services)
instead. You can do this like below:
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();
}
You can then modify your Configure()
method to receive IServiceProvider
, you can get the instance of UrlHelper
by then doing the following.
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider) {
//Code removed for brevity
var urlHelper = serviceProvider.GetService<IUrlHelper>(); <-- helper instance
app.UseMvc();
}
Note: Place this after the services.Mvc()
来源:https://stackoverflow.com/questions/49531791/get-urlhelper-in-middleware-asp-net-mvc-core-2-0