如何为/新闻/ 5的路由映射到我的新闻控制器 [英] How to map a route for /News/5 to my news controller

查看:97
本文介绍了如何为/新闻/ 5的路由映射到我的新闻控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何为/新闻/ 5的路由映射到我的新闻控制器。

I am trying to identify how to map a route for /News/5 to my news controller.

这是我的NewsController:

This is my NewsController:

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

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

}

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

This is my Global.asax.cs rule:

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

我试着去/新闻/ 5,但我收到一个资源未找到错误,但是当进入/新闻/索引/ 5它的工作原理?

I try to go to /News/5 but I receive a resource not found error, however when going to /News/Index/5 it works?

我已经尝试过 {控制器} / {ID} 但只是产生了同样的问题。

I have tried just {controller}/{id} but that just produced the same issue.

谢谢!

推荐答案

{控制器} / {ID} 的路线是正确的,但你problaby注册它的另一路由后。在路由列表它搜索自上而下找到胜利的第一场比赛。

Your {controller}/{id} route was correct but you problaby registered it AFTER the other route. In the route list it searches top down and the first match it finds wins.

要帮助引导路由我会建议创建路径约束是为了确保#1控制器中是否存在和#2 {ID} 是一个数字。

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.

请参阅本文

主要是:

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

这篇关于如何为/新闻/ 5的路由映射到我的新闻控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆