[英]ASP.NET Core Razor Pages Endpoint Routing for all Paths after Page Name in URL
So, I'm adapting an MCV example to a Razor Pages application, and have everything working now except for endpoint routing.因此,我正在将 MCV 示例改编为 Razor Pages 应用程序,并且除了端点路由外,现在一切正常。
Desired behavior:期望的行为:
All text in the URL after the desired page name will be passed to that page's OnGet action as an input variable.
URL 中所需页面名称之后的所有文本都将作为输入变量传递给该页面的 OnGet 操作。
eg HTTP://application.tld/Reports/Static/any/text/that/follows is handle by the Static.cshtml.cs page's OnGet(string viewPath) and passes "any/text/that/follows" as the viewPath input variable
例如 HTTP://application.tld/Reports/Static/any/text/that/follows 由 Static.cshtml.cs 页面的 OnGet(string viewPath) 处理并传递“any/text/that/follows”作为 viewPath 输入多变的
Actual behavior:实际行为:
It tries to find a page at the full location, /Reports/Static/any/text/that/follows, which doesn't exist, so it returns a 404 error.
它尝试在完整位置 /Reports/Static/any/text/that/follows 找到一个页面,该页面不存在,因此它返回 404 错误。
Using:使用:
In the MCV example app startup.cs:在 MCV 示例应用程序 startup.cs 中:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
//Because everything after "Explorer/" is our path and path contains
//some slashes and maybe spaces, so we can use "Explorer/{*path}"
routes.MapRoute(
name: "Explorer",
template: "Explorer/{*path}",
defaults: new { controller = "Explorer", action = "Index" });
});
then in the controller然后在 controller
public IActionResult Index(string path)
In the Razor Pages app startup.cs:在 Razor Pages 应用程序 startup.cs 中:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "static",
pattern: "/Reports/Static/{*viewPath}",
defaults: new { page = "/Reports/Static", action = "OnGet" });
});
then in the page然后在页面中
public IActionResult OnGet(string viewPath)
Suggestions on how to get this working?关于如何使它工作的建议?
TIA:0) TIA:0)
Edit with my final solution, with much thanks to @Sergey, and with a catch-all since the number of segments will be variable:使用我的最终解决方案进行编辑,非常感谢@Sergey,并且因为段的数量是可变的,所以要全面了解:
(1) nothing needed for this in the startup.cs so I removed the "endpoints.MapControllerRoute()" section (1) 在 startup.cs 中不需要任何东西,所以我删除了“endpoints.MapControllerRoute()”部分
(2) keep in the page's cshtml.cs file (2) 保存在页面的cshtml.cs文件中
public IActionResult OnGet(string viewPath)
(3) and then add in the page's cshtml file (3)然后在页面的cshtml文件中添加
@page "{*viewPath}"
If you use razor pages you have to put to the top of your page:如果您使用 razor 页面,则必须将其放在页面顶部:
@page "{any}/{text}/{that}/{follows}"
//or you can use some nullables
@page "{any}/{text?}/{that?}/{follows?}"
````
in the code behind the page in the action OnGet or OnGetAsync:
````
public async Tast<IActionResult> OnGetAsync( string any, string text, ....)
````
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.