【问题标题】:How to map a route for /News/5 to my news controller如何将 /News/5 的路由映射到我的新闻控制器
【发布时间】:2012-03-09 01:49:00
【问题描述】:

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

这是我的 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} 时,您是否保留了默认设置? new { controller = "News", action = "Index", id = -1 }

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


【解决方案1】:

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

为了帮助引导路由,我建议为此创建路由约束,以确保 #1 控制器存在并且 #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+" }
    ); 

【讨论】:

  • 非常感谢,我在 8 分钟内无法接受您的消息,但我会回来的。您解决了我的约束问题:new { controller = "News", id = @"0|-?[1-9]\d*" } // Route constraints 并将其移动到其他地图路线上方
【解决方案2】:

你需要确保你的新路由在你的默认路由之前,像这样:

    routes.MapRoute(
        "NewsAbbr", // Route name
        "{controller}/{id}", // URL with parameters
        new { controller = "News", action = "Index", id = -1 } // Parameter defaults
    );


    routes.MapRoute(
        "News", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "News", action = "Index", id = -1 } // Parameter defaults
    );

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2021-09-21
    • 1970-01-01
    相关资源
    最近更新 更多