默认路由不起作用

时间:2012-05-03 16:51:55

标签: asp.net-mvc-3 routing

为什么这不起作用?

路线:

routes.MapRoute(
                "Summary",
                "{controller}/{id}",
                new { controller = "Summary", action = "Default" }
            );

控制器:

public class SummaryController : Controller
    {
        public ActionResult Default(int id)
        {
            Summary summary = GetSummaryById(id);

            return View("Summary", summary);
        }
    }

URL:

http://localhost:40353/Summary/107

错误:

Server Error in '/' Application.

    The resource cannot be found.

    Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly. 

    Requested URL: /Summary/107

    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225

更新

让我用更聪明的问题更新问题。我怎么能同时拥有这两个?

routes.MapRoute(
                    "Home",
                    "{controller}",
                    new { controller = "Home", action = "Default" }
                );

routes.MapRoute(
                    "Summary",
                    "{controller}/{id}",
                    new { controller = "Summary", action = "Default" }
                );

2 个答案:

答案 0 :(得分:11)

路由如何工作(默认情况下)?

让我们回到默认路线,这有点像这样:

routes.MapRoute(

    // Route name
    "Default", 

    // URL with parameters
    "{controller}/{action}/{id}", 

    // Parameter defaults
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } 

);

让我们试着理解这个是如何运作的。

  • 如果您访问/,则会调用Index控制器的Home操作;省略了可选的ID。

  • 如果您访问/C,则会调用Index控制器的C操作;省略了可选的ID。

  • 如果您访问/C/A,则会调用A控制器的C操作;省略了可选的ID。

  • 如果您访问/C/A/1,则会调用标识为A的{​​{1}}控制器的C操作。

因此,该路由允许1//C/C/A形式的任何网址,其中/C/A/1是控制器,{{1}是一个动作。这是什么意思?这意味着您不必必须指定自己的路线。

因此,如果没有路由,您可以拥有CA,并向最后一个名为HomeController的控制器添加操作。

然后SummaryController会调用Show


如果我想为控制器设置更短的路径(/ Controller / Id)怎么办?

假设我们确实要映射路由,以便/Summary/Show/1调用SummaryController.Show(1)

以下是正确的表格:

/Summary/1

请注意,我们已将SummaryController.Show(1)路线更改为routes.MapRoute( "Summary", "Summary/{id}", new { controller = "Summary", action = "Show" } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); 路线。现在我们添加了Home路由,我们告诉Default格式的网址会触发该路由。当他们这样做时,它会调用Summary控制器的Summary/{id}操作并传递Show作为参数;这正是你想要的......

另请注意,我们需要先放置Summary路线,使其优先。

警告:您不希望为您创建的每个操作创建新路由。您也不希望所有操作都在同一个控制器中。如果其中一个是这种情况,请考虑重新考虑您的方法,以便您以后不会遇到问题......

答案 1 :(得分:0)

尝试更换:

new { controller = "Summary", action = "Default" }

with:

new { controller = "Summary", action = "Default", id = UrlParameter.Optional }

编辑:尝试了您的代码,为我工作。您是否在global.asax中定义了其他路由?

相关问题