C# 如何从启动时获取ASP.NET Core 2中的Url.Action?
在ASP.net Core 2 MVC应用程序中,是否可以从Startup类的public void Configure方法中获取具有URL.Action类型的URL 如果是,怎么做 代码如下:C# 如何从启动时获取ASP.NET Core 2中的Url.Action?,c#,asp.net-core,C#,Asp.net Core,在ASP.net Core 2 MVC应用程序中,是否可以从Startup类的public void Configure方法中获取具有URL.Action类型的URL 如果是,怎么做 代码如下: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseStaticFiles(); app.UseAuthenticat
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Request.Path = "/Home"; // <==== Url.Action("", "")...
await next();
}
});
}
public void配置(IApplicationBuilder应用程序、IHostingEnvironment环境、iLogger工厂)
{
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(路由=>
{
routes.MapRoute(
名称:“默认”,
模板:“{controller=Home}/{action=Index}/{id?}”);
});
应用程序使用(异步(上下文,下一步)=>
{
等待下一个();
if(context.Response.StatusCode==404)
{
context.Request.Path=“/Home”//我知道这是一个老问题,但答案是使用UrlHelper背后的底层实用程序:
var generator=app.ApplicationServices.GetRequiredService();
var controllerName=nameof(HomeController).Replace(“Controller”,“”);
var url=generator.GetPathByAction(name of(HomeController.Index),controllerName)
注意:在上面的示例代码中,我发现您必须自己从控制器类名中删除控制器位,否则结果将为空。您是否可以使用DI注入IUrlHelper?app.ApplicationServices.GetService()。操作(“,”);不,不起作用:(旁注,在管道末尾调用next有些徒劳,尤其是再次调用它。MVC在您前面,您不能调用next并期望它接收请求。有一个状态码中间件,它可以执行类似操作,但您可以将其放在MVC之前。
var generator = app.ApplicationServices.GetRequiredService<LinkGenerator>();
var controllerName = nameof(HomeController).Replace("Controller", "");
var url = generator.GetPathByAction(nameof(HomeController.Index), controllerName)