c# - 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 错误。
使用:
- Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation 版本="5.0.3"
- Microsoft.AspNetCore.Session 版本="2.2.0"
- Microsoft.EntityFrameworkCore 版本="5.0.3"
在 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}"
解决方案
如果您使用剃须刀页面,则必须将其放在页面顶部:
@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, ....)
````
推荐阅读
- arrays - 如何保存函数的返回数组?
- google-apps-script - 如何在插入大量数据时修复“访问文档时服务文档失败”?
- java - 在 JavaCC 中我的解析器中缺少什么文本?
- javascript - JavaScript:如何读取本地文件(特别是 json 文件)?
- r - 您如何使用 dplyr::pull 将分组的列转换为向量?
- php - 如何修复 wordpress 在在线网站上卷曲
- javascript - 如何将 selected:clear 过滤器放入作为 JSON 加载的画布中?
- r - 如何从R中的列中提取一个文本元素?
- python - extract_first 仅导致第一项仅 .extract() 不起作用
- javascript - 如何从数组中排除元素?