首页 > 解决方案 > ASP.NET Core 3.0 包罗万象的路由意外行为

问题描述

最近我遇到了一些意想不到的问题

我正在使用 ASP.NET Core 3.0,并在 StartUp.cs 中定义了两条路由

启动.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}");
    });

文件控制器.cs

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

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

请求文件/文件夹/abc/abc我希望匹配第一个路由,但结果是 404 not found

但是如果我改变了路线的顺序

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

这行得通!

我的问题是为什么如果我在顶部定义{controller=File}/folder/{*path}第一个版本不起作用

我以为它会按顺序检查路由表

标签: asp.net-core

解决方案


一般来说,我们总是将客户路由器放在默认路由之前。对于这个问题,如果我们在默认路由之前放置非包罗万象的路由,它将按预期工作。但是,如果我们将包罗万象的路由放在默认路由之前,您会发现当我们通过文件/文件夹/abc/abc 访问时您找不到任何页面。这个问题在 asp.net core 3.0 中不存在,但在 asp.net core 2.0 和 MVC 项目中也存在。如果您需要使用包罗万象的路线,最好将它们放在后面的路线表中。您还可以阅读这篇文章了解更多详细信息:多条路线。这将有助于解决未知问题。


推荐阅读