asp.net-core - 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}第一个版本不起作用
我以为它会按顺序检查路由表
解决方案
一般来说,我们总是将客户路由器放在默认路由之前。对于这个问题,如果我们在默认路由之前放置非包罗万象的路由,它将按预期工作。但是,如果我们将包罗万象的路由放在默认路由之前,您会发现当我们通过文件/文件夹/abc/abc 访问时您找不到任何页面。这个问题在 asp.net core 3.0 中不存在,但在 asp.net core 2.0 和 MVC 项目中也存在。如果您需要使用包罗万象的路线,最好将它们放在后面的路线表中。您还可以阅读这篇文章了解更多详细信息:多条路线。这将有助于解决未知问题。
推荐阅读
- c++ - (C++) 如果用户已经在 main 中输入了值,如何将局部变量从 main 传递到另一个函数的主体?
- react-native - 如何使用 @react-navigation/native 删除 react native 中的上一页
- r - 当列不存在时运行代码(尽管最后有一个数字)?- 使困惑
- c# - 定义触发器列表以执行作业
- kotlin - 如何抛出异常并记录为信息?
- c# - WPF 将不同的形状绑定到 ItemsControl 中的 DataTemplate
- sql - 在 SQL 中使用 SELECT 设置变量值时出错
- java - Hibernate 仅检索一列,其他列为空
- r - 在数据框中查找包含另一个数据框行的所有元素的行
- nginx - 如何删除“www.” 来自 $ssl_server_name