【问题标题】:MVC 5 routing with 1 parameter带有 1 个参数的 MVC 5 路由
【发布时间】:2015-05-15 17:18:36
【问题描述】:

我希望网址是

domain.com/doc/{project}

我有一个名为 Projects 或“ProjectsController.cs”的控制器。 这个控制器有一个动作(ActionResult),我想通过我的自定义 url 路由访问,称为“DocumentationIndex”。

DocumentationIndex 确实有一个参数。这是一个简单的字符串参数。

以下继续给我一个 404。

routes.MapRoute(
    name: "Documentation",
    url: "doc/{project}",
    defaults: new { controller = "Projects", action = "DocumentationIndex", project = "" }
);

谁能指出我正确的方向?

【问题讨论】:

  • 抛出的异常是什么,异常的消息是什么,异常的堆栈跟踪是什么。

标签: c# asp.net-mvc


【解决方案1】:

您可以使用属性路由在控制器中定义它:

public class ProjectsController 
{
     [Route("doc/{*project}")]
     public ActionResult DocumentationIndex(string project = "") 
     { // ... }
}

您需要确保在路由配置中启用属性路由:

routes.MapMvcAttributeRoutes();

{*projects} 中的 * 将确保路由参数与 URL 的其余部分匹配,即使它包含特殊字符。

【讨论】:

  • 谢谢!但是我有一个非常愚蠢的问题。如果字符串参数中有点怎么办?如,“domain.com/doc/Project.v.2.1” 路由似乎与一个单词参数一起工作正常。
  • 不幸的是,* 没有任何区别。 404 错误继续存在。没有特殊字符字符串的简单单词仍然有效。
  • 通过将以下内容添加到 web.config 来修复点 (.) 问题。 <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> </system.webServer>
【解决方案2】:

试试这个:

routes.MapRoute(
    "Documentation",
    "doc/{project}",
    new { controller = "Projects", action = "DocumentationIndex" }
);

您的控制器代码:

public class ProjectsController ... {
    //
    public ActionResult DocumentationIndex(string project = "") {
        // ...
    }
}   

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-24
    • 2014-10-13
    • 2015-04-17
    • 2013-11-06
    • 2021-09-28
    • 2011-06-30
    • 2014-12-07
    • 2014-03-19
    相关资源
    最近更新 更多