【问题标题】:Allow empty parameter in MVC route在 MVC 路由中允许空参数
【发布时间】:2010-12-15 06:07:50
【问题描述】:

我有一条只能由自动化进程调用的路由:

routes.MapRoute(
  "Automated file processing",
  "Process/{change}/{file}/{type}",
  new { controller = "C", action = "Process" }
);

filetype 都是可选参数。理想情况下,我希望能够打电话

/Process/Created/Filename/Text    (with file and type)
/Process/DirectoryListing//Text   (with type only)
/Process/Created/Filename/        (with file only)

您将如何实现中间的可选参数?使用我展示的示例路线,即使我将file = "", type = "" 添加到路线中,我也会得到:

HTTP 错误 400 - 错误请求。

【问题讨论】:

标签: asp.net-mvc routes string


【解决方案1】:

路径中间不能有可选参数。出于显而易见的原因,只有 最后一个 参数可以是可选的,否则路由引擎无法区分不同的可能情况。

【讨论】:

    【解决方案2】:

    你的答案就在这里:http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

    它讨论了问题并提供了解决方法, 希望有帮助!

    【讨论】:

    • 抱歉,那篇文章讨论了 MVC 3 中完全不同的问题。
    【解决方案3】:

    相信你需要加file = UrlParameter.Optional, type = UrlParameter.Optional

    对于可选的中间参数,我会在此之前定义另一条路线。

    【讨论】:

    • 我认为file = UrlParameter.Optional 修复了两者都丢失的情况,但不是我缺少中间参数的情况(以及网址中的//)。我将如何定义另一条路线? Process/{change}//{type} 不起作用。
    • 是的,那是行不通的。你可以做 ..../file-{file}/type-{type},查询字符串参数或类似的东西。
    猜你喜欢
    • 2013-01-22
    • 2019-01-14
    • 1970-01-01
    • 2019-07-22
    • 2014-02-09
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多