asp.net - 如何将/News/5 的路由映射到我的新闻 Controller

标签 asp.net asp.net-mvc routes asp.net-mvc-4

我正在尝试确定如何将/News/5 的路由映射到我的新闻 Controller 。

这是我的 NewsController:

public class NewsController : BaseController
{
    //
    // GET: /News

    public ActionResult Index(int id)
    {
        return View();
    }

}

这是我的 Global.asax.cs 规则:
        routes.MapRoute(
            "News", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "News", action = "Index", id = -1 } // Parameter defaults
        );

我尝试转到/News/5 但我收到一个资源未找到错误,但是当转到/News/Index/5 时它是否有效?

我只试过 {controller}/{id}但这只是产生了同样的问题。

谢谢!

最佳答案

您的 {controller}/{id}路线是正确的,但您可能在另一条路线之后注册了它。在路线列表中,它自上而下搜索,找到的第一个匹配项获胜。

为了帮助引导路由,我建议为此创建路由约束以确保 #1 Controller 存在和 #2 {id}是一个数字。

this article

主要是:

 routes.MapRoute( 
        "Index Action", // Route name 
        "{controller}/{id}", // URL with parameters EDIT: forgot starting "
        new { controller = "News", action = "Index" },
        new {id= @"\d+" }
    ); 

关于asp.net - 如何将/News/5 的路由映射到我的新闻 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9332026/

相关文章:

node.js - 如何在快速路由中指定可选参数名称?

routes - 在 Ember 中定义资源路由的正确方法?

c# - 如果文件夹不存在,则创建它

asp.net - EF 模型和代码使用者之间存储库的使用

c# - 如何添加带有按钮单击事件 MVC 的新表?

c# - 为采用 List 的 Html.EditorFor 指定模板名称

php - CakePHP动态路由配置,可能吗?或者只是一个梦想?

asp.net - 2010 年在 ASP.NET 中进行客户端/服务器验证的最佳方法是什么?

c# - 动态 HTML 内容 - "A potentially dangerous Request.Form value was detected from the client"

asp.net-mvc - MVC3 中的 "No overload for method ' LabelFor ' takes 2 arguments"