简体   繁体   English

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

[英]How to map a route for /News/5 to my news controller

I am trying to identify how to map a route for /News/5 to my news controller. 我正在尝试确定如何将/ News / 5的路由映射到我的新闻控制器。

This is my NewsController: 这是我的NewsController:

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

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

}

This is my Global.asax.cs rule: 这是我的Global.asax.cs规则:

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

I try to go to /News/5 but I receive a resource not found error, however when going to /News/Index/5 it works? 我尝试去/ News / 5但是我收到了资源未找到错误,但是当进入/ News / Index / 5时它有效吗?

I have tried just {controller}/{id} but that just produced the same issue. 我只试过{controller}/{id}但这只是产生了同样的问题。

Thanks! 谢谢!

Your {controller}/{id} route was correct but you problaby registered it AFTER the other route. 您的{controller}/{id}路由是正确的,但是您在另一条路线之后注册了它。 In the route list it searches top down and the first match it finds wins. 在路线列表中,它自上而下搜索并找到匹配的第一个匹配。

To help steer routing I would suggest creating route constraints for this to ensure that #1 the controller exists and #2 the {id} is a number. 为了帮助引导路由,我建议为此创建路由约束,以确保#1控制器存在,#2 {id}是一个数字。

See this article 看到这篇文章

Mainly: 主要是:

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

You need to make sure your new route is before your default route, like so: 您需要确保新路由在默认路由之前,如下所示:

    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
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM