简单的MVC路由问题

时间:2010-01-26 11:10:09

标签: asp.net-mvc model-view-controller routing url-routing

我有几页与其他页面非常相似,但其中一页不起作用。

当我写'http://localhost:2265/Segment/'时,我收到恼人的错误消息“'/'应用程序中的服务器错误。 无法找到资源。“

http://localhost:2265/User/”等其他网页效果非常好,而且“http://localhost:2265/Segment/Create”也是如此。所以细分的索引就是问题所在。我已经使用了ASP.NET路由调试器,而在其他页面上我得到了正确的映射,但是在使用调试器时我也得到了同样的错误消息“无法找到资源”。我认为这表明默认路由也没有捕获它。

有什么想法吗?

这是我的MapRoute命令。

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

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

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

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

更新

感谢您的快速回复!

我删除了除默认路由之外的所有路由。它没有解决问题,但现在路线列表更短了。

我的控制器文件中有其他类,如下所示:

public class SegmentFormViewModel
{
}

public class SegmentController : Controller
{
}

public class SegmentFormCreateModel : Segment
{
}

我试图将它移到控制器内部,但这也无济于事。

有没有办法调试这个问题?

更新

这是我的控制器(没有方法的内容)

public class SegmentController : Controller
{
    //
    // GET: /Segment/

    public ActionResult Index()
    {
    }

    //
    // GET: /Segment/Details/5

    public ActionResult Details(Guid id)
    {
    }

    //
    // GET: /Segment/Create

    public ActionResult Create()
    {
    }

    //
    // POST: /Segment/Create

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(FormCollection collection)
    {
    }

    //
    // GET: /Segment/Edit/5

    public ActionResult Edit(int id)
    {
    }

    //
    // POST: /Segment/Edit/5

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection collection)
    {
    }
}

2 个答案:

答案 0 :(得分:4)

要匹配您的/ Segment /路由,您需要一个“SegmentController”控制器类来接受GET请求的“索引”操作,即不受[AcceptVerbs(HttpVerbs.Post)]限制。

正如Darin已经评论过的那样,默认路由将处理您添加的所有其他路由,因此您不需要额外的路由。

更新后:
您的问题可能与Segment控制器中的操作有关。您在哪个类中使用哪个类并不重要。你在Segment控制器中有什么行动?

第二次更新后:
你的行为看起来不错,所以我怀疑问题出在你没有列出的代码中 后续步骤:
1.使用已经提到的路由器调试器 2.下载MVC源,以便您可以逐步完成它 最后的手段:启动一个全新的项目,只添加Segment控制器。然后继续添加相关代码,直到找到问题为止。

答案 1 :(得分:2)

使用Phil Haack's RouteDebugger。它会告诉你匹配的内容,这通常可以很快解决问题。

设置起来非常简单:在您的/ bin文件夹中删除RouteDebug.dll并对您的App Start事件进行此更改:

protected void Application_Start(object sender, EventArgs e)
{
  RegisterRoutes(RouteTable.Routes);
  RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
}