首页 > 解决方案 > URL 中页面名称后所有路径的 ASP.NET Core Razor 页面端点路由

问题描述

因此,我正在将 MCV 示例改编为 Razor Pages 应用程序,并且现在一切正常,除了端点路由。

期望的行为:

URL 中所需页面名称之后的所有文本都将作为输入变量传递给该页面的 OnGet 操作。

例如 HTTP://application.tld/Reports/Static/any/text/that/follows 由 Static.cshtml.cs 页面的 OnGet(string viewPath) 处理,并将 "any/text/that/follows" 作为 viewPath 输入多变的

实际行为:

它尝试在完整位置 /Reports/Static/any/text/that/follows 找到一个页面,该页面不存在,因此它返回 404 错误。

使用:

在 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" });
            });

然后在控制器中

            public IActionResult Index(string path)

在 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" });
            });

然后在页面中

            public IActionResult OnGet(string viewPath)

关于如何使它工作的建议?

TIA :0)


使用我的最终解决方案进行编辑,非常感谢@Sergey,并且因为段的数量是可变的,所以要全面了解:

(1) 在 startup.cs 中不需要任何东西,所以我删除了“endpoints.MapControllerRoute()”部分

(2) 保存在页面的cshtml.cs文件中

            public IActionResult OnGet(string viewPath)

(3)然后在页面的cshtml文件中添加

            @page "{*viewPath}"

标签: c#asp.netrazor

解决方案


如果您使用剃须刀页面,则必须将其放在页面顶部:

@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, ....)
````

推荐阅读