如何将/ News/5的路由映射到我的新闻控制器

Elv*_*ike 13 asp.net asp.net-mvc routes asp.net-mvc-4

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

这是我的NewsController:

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

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

}
Run Code Online (Sandbox Code Playgroud)

这是我的Global.asax.cs规则:

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

我尝试去/ News/5但是我收到了资源未找到错误,但是当进入/ News/Index/5时它有效吗?

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

谢谢!

Nic*_*ork 18

你的{controller}/{id}路线是正确的,但你的问题是在另一条路线后注册的.在路线列表中,它自上而下搜索并找到匹配的第一个匹配.

为了帮助引导路由,我建议为此创建路由约束,以确保控制器存在#1,#2 {id}是数字.

看到这篇文章

主要是:

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


小智 6

您需要确保新路由在默认路由之前,如下所示:

    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
    );
Run Code Online (Sandbox Code Playgroud)