c# - 属性路由在 MVC4 中不起作用

标签 c# asp.net-mvc-4 asp.net-mvc-routing attributerouting

我在 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。

  1. localhost:(port)/test-temp-1

  2. 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/

相关文章:

c# - 如何使用 LINQ 获取列表中属性的平均值?

c# - 更改 Google 身份验证请求的语言 - Oauth 2.0

c# - 从 ContextMenu 绑定(bind)到父 DataContext

c# - 如何在 asp.net mvc 域名/用户名中进行路由,以便每个用户都像 facebook 一样拥有他的 "username"

asp.net-mvc-routing - 如何在MapHttpRoute中设置默认 namespace ?

asp.net-mvc - 如何在asp.net mvc 4中自定义路由

c# - Word OpenXML 替换标记文本

javascript - 为什么我的日期输入没有读取模型值?

c# - 如何播放下载的 mp3 文件?

c# - 带有排序数据的 mvc razor foreach