简体   繁体   中英

Razor Page routing via DynamicRouteValueTransformer always returns 404

I'm using a custom dynamic route transformer in an ASPNET Core 5 Razor Pages app. 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.

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

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

My LaunchPageTransformer:DynamicRouteValueTransformer implementation:

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

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

And in 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.

There are 2 things wrong in your code. Firstly MapDynamicControllerRoute is used for selecting a controller action, not for selecting a page handler. What you need to use is MapDynamicPageRoute . Secondly the value for page route key should be a path starting with / . So instead of "Test" , you need "/Test" .

Here's the final code you need (replacing your code):

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

Inside your implementation of LaunchPageTransformer :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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