c# - 仅使用 'x' 前缀引起的神秘 404 路由错误?

标签 c# asp.net-mvc asp.net-mvc-5 url-routing asp.net-mvc-routing

我想让我的 URL 尽可能短,所以我正在测试没有分隔符的路由,如下所示:

routes.MapRoute(
   name: "Photo",
   url: "x{id}",
   defaults: new { controller = "Content", action = "Photo" }
);

由于某些原因,上面的路由不起作用,我收到 404 错误:

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.

但是,当我为另一个字母更改 x 前缀时,比如 g,它工作正常。

没有冲突的路线。请问我在这里缺少什么?

编辑:

我再次看到这个问题,我观察到 404 可能仅在 id 包含 x 时发生,即像 /xa1B2 这样的路由> 或 /xZ9y8 完美运行,但 x12xG 失败。有什么想法吗?

最佳答案

根据 MSDN :

You can define more than one placeholder between delimiters, but they must be separated by a constant value. For example, {language}-{country}/{action} is a valid route pattern. However, {language}{country}/{action} is not a valid pattern, because there is no constant or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the language placeholder from the value for the country placeholder.

如您所述,当您的 ID 以 x 开头时会发生错误。这是因为它无法区分您的 ID 值和您选择的常数之间的差异。

您可以使用一些选项来解决此问题:

  1. 在常量和占位符之间放置一个分隔符,该分隔符不会作为任何“id”的第一个字符出现。
  2. 为常量选择一个字符,该字符不会作为任何“id”的第一个字符出现。
  3. 更改“id”,使其不能以 x 开头。
  4. 添加一条重复路线,当“id”包含 x 时,一条路线带有绕过约束,第二条路线以另一个字符开始。

第四个选项看起来像这样:

// Ids that don't contain x will use this route
routes.MapRoute(
   name: "Photo_X",
   url: "x{id}",
   defaults: new { controller = "Content", action = "Photo" },
   constraints: new { id = @"(?i)[^x]" }
);

// Ids that contain x will use this route instead
routes.MapRoute(
   name: "Photo_Y",
   url: "y{id}",
   defaults: new { controller = "Content", action = "Photo" }
);

关于c# - 仅使用 'x' 前缀引起的神秘 404 路由错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25877988/

相关文章:

c# - MVC 动态更改 ViewName

c# - 为什么我不断收到 Analytics API 的 403 用户没有足够的权限来访问此配置文件错误

c# - 有没有办法将 C# 泛型字典拆分成多个字典?

c# - 在 foreach 循环中更改另一个结构内的结构

javascript - 在 mvc 中加载 View 时调用 javascript 函数

jquery - 如何在 MVC5 View 中使用 jquery Accordion

javascript - 如何在mvc 5中基于静态下拉列表过滤数据库记录

javascript - 如何获取客户端通过 HTTP GET 请求传递的参数?

c# - 使用 Code-First MVC5 EF6 在 SQL 表中存储 DateTime 属性而不是字节数组

c# - 每种角色类型的不同默认页面/ Controller - MVC 5