我在 MVC4
应用程序中使用 Attribute Routing
。我已将路由设置为 [Route("test-{testParam1}-{testParam2}")]
。这里“{testParam2}”可能包含单词“test”。例如,如果我输入如下网址,
localhost:33333/test-temp-test-tempparam2
这给了我 404 错误。在 url 中,{testParam2}
将两个单词 test tempparam2
格式化为 test-tempparam2
。当test
word 位于{testParam2}
的最后位置时,它运行良好。这意味着如果 url 像 .../test-temp-tempParam2-test
运行良好。但是下面给出错误。 .../test-temp-test-tempParam2
.
下面是可能有帮助的代码...
[Route ("test-{testParam1}-{testParam2}")]
public ActionResult Foo (int testParam2) {...}
现在尝试访问两个 url。
localhost:(port)/test-temp-1
localhost:(port)/test-test-temp-1
在我的例子中,第二个给出了错误。在这种情况下,第一个参数被格式化为 test-temp
from test temp
。第一次运行良好。
如何解决这个问题?
最佳答案
OP 指出路由模板中的最后一个参数是一个int
使用路由约束。
路由约束让您限制路由模板中参数的匹配方式。一般语法是 {parameter:constraint}
。例如:
[Route ("test-{testParam1}-{testParam2:int}")]
public ActionResult Foo (int testParam2) {...}
因此,当尝试跟踪两个 URL 时。
localhost:(port)/test-temp-1
localhost:(port)/test-test-temp-1
第一个匹配路由数据{testParam1 = temp}-{testParam2 = 1}
第二个匹配路由数据{testParam1 = test-temp}-{testParam2 = 1}
关于c# - 属性路由在 MVC4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41736633/