我想让我的 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 值和您选择的常数之间的差异。
您可以使用一些选项来解决此问题:
- 在常量和占位符之间放置一个分隔符,该分隔符不会作为任何“id”的第一个字符出现。
- 为常量选择一个字符,该字符不会作为任何“id”的第一个字符出现。
- 更改“id”,使其不能以
x
开头。 - 添加一条重复路线,当“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/