是否可以从 ASP.net Core 2 MVC 应用程序中 Startup 类的 public void Configure 方法获取带有 Url.Action 类型的 URL?
如果是,怎么做到的?
这里是代码:
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();
}
});
}
最佳答案
我知道这是一个老问题,但答案是使用 UrlHelper 背后的底层实用程序:LinkGenerator :
var generator = app.ApplicationServices.GetRequiredService<LinkGenerator>();
var controllerName = nameof(HomeController).Replace("Controller", "");
var url = generator.GetPathByAction(nameof(HomeController.Index), controllerName)
请注意,在上面的示例代码中,我发现您必须自己从 Controller 类名称中删除 Controller 位,否则结果将为空。
关于c# - 如何从启动中获取 ASP.NET Core 2 中的 Url.Action?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47042600/