简体   繁体   English

Razor 通过 DynamicRouteValueTransformer 的页面路由总是返回 404

[英]Razor Page routing via DynamicRouteValueTransformer always returns 404

I'm using a custom dynamic route transformer in an ASPNET Core 5 Razor Pages app.我在 ASPNET Core 5 Razor Pages 应用程序中使用自定义动态路由转换器。 My TransformAsync override is called as expected and returns a custom route to a page, but that page is never loaded, and the request always returns 404. Either Razor pages can't find the page I'm routing to, or it's just ignoring my custom route.我的 TransformAsync 覆盖按预期调用并返回到页面的自定义路由,但该页面从未加载,并且请求始终返回 404。Razor 页面找不到我要路由到的页面,或者它只是忽略了我的自定义路线。

Here's a simple test case.这是一个简单的测试用例。 Any tips on what might be wrong, or how I can troubleshoot would be greatly appreciated!任何关于可能出错的提示,或者我如何排除故障,将不胜感激!

In Startup.Configure(..) I have在 Startup.Configure(..) 我有

app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapDynamicControllerRoute<LaunchPageTransformer>("{**id}");
});

My LaunchPageTransformer:DynamicRouteValueTransformer implementation:我的 LaunchPageTransformer:DynamicRouteValueTransformer 实现:

public override async ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext, RouteValueDictionary values)
{
   return await Task.Run(() =>
   {
       return new RouteValueDictionary()
       {
           { "page", "Test" },
           { "id", "123" }
       };
   });
}

In Pages/Test.cshtml I have在 Pages/Test.cshtml 我有

@page "{id}"
@model Launch.Pages.TestModel
@{
}

And in Pages/Test.cshtml.cs:在 Pages/Test.cshtml.cs 中:

public class TestModel : PageModel
{
   public void OnGet(int? id)
   {
   }
}

I'm navigating to localhost:44351/123, which successfully selects my transformer but does nothing with the results.我正在导航到 localhost:44351/123,它成功地选择了我的转换器,但对结果没有任何作用。

There are 2 things wrong in your code.您的代码中有两处错误。 Firstly MapDynamicControllerRoute is used for selecting a controller action, not for selecting a page handler.首先MapDynamicControllerRoute用于选择 controller 动作,而不是用于选择页面处理程序。 What you need to use is MapDynamicPageRoute .您需要使用的是MapDynamicPageRoute Secondly the value for page route key should be a path starting with / .其次, page路由键的值应该是以/开头的路径。 So instead of "Test" , you need "/Test" .因此,您需要"/Test"而不是"Test" Test" 。

Here's the final code you need (replacing your code):这是您需要的最终代码(替换您的代码):

endpoints.MapDynamicPageRoute<LaunchPageTransformer>("{**id}");

Inside your implementation of LaunchPageTransformer :LaunchPageTransformer的实现中:

return new RouteValueDictionary()
{
    //we need to use a / to prefix the page name here
    { "page", "/Test" },
    { "id", "123" }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM