Boyi
Boyi

Reputation: 23

ASP.NET Core 3.0 catch-all route unexpected behavior

Recently i encounter some unexpected issue

I'm using ASP.NET Core 3.0 and i defined two routes in StartUp.cs

StartUp.cs

   app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "file",
            pattern: "{controller=File}/folder/{*path}",
            new { Action = "Folder" });

        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=File}/{action=Index}/{filename}");
    });

FileController.cs

public class FileController : Controller
{
    public IActionResult Folder(string path)
    {
        return Ok(path);
    }

    public IActionResult Index(string filename)
    {
        return Ok(filename);
    }
}

request to file/folder/abc/abc i expected to match first route but the result was 404 not found

but if i changed order of route

   app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=File}/{action=Index}/{filename}");

        endpoints.MapControllerRoute(
            name: "file",
            pattern: "{controller=File}/folder/{*path}",
            new { Action = "Folder" });
    });

It work!

My questing is why first version don't work if i defined {controller=File}/folder/{*path} on top

I thought it will check route table sequentially

Upvotes: 0

Views: 421

Answers (1)

DevPreSupport_MSFT
DevPreSupport_MSFT

Reputation: 282

In general we always put customer routers before default route. For this issue if we put non catch-all route before default route it will work as expect. However if we put catch-all route before default route you will see that you could not find any pages when we access via file/folder/abc/abc. This issue is not existed in asp.net core 3.0 but also in asp.net core 2.0 and MVC project. If you need to use catch-all routes, it is better to put them later in the route talbe. You could also read this article for more details: Multiple routes. It will help to fix unknown issues.

Upvotes: 1

Related Questions