如何知道MVC.NET尝试查找的URL

时间:2015-01-08 11:10:54

标签: asp.net-mvc asp.net-mvc-4

我的MVC4应用程序有一个表单。在此,人们从选择框中选择标准,然后单击搜索。

此时,它会指向控制器,控制器将值存储为TempData,然后重定向到正确的目标网页。

因此,从View中,单击搜索按钮后,路径就是我的ProductController中的Shoes

    [HttpGet]
    public ActionResult Shoes(Shoe shoe)
    {

        TempData["shoe"] = shoe;

        return RedirectToAction("Index", "Shoes", new  { SelectedSize = shoe.SelectedSize, SelectedColour = shoe.SelectedColour });

    }

以上重定向到

    [HttpGet]
    public ActionResult Index(Shoes shoes, int startIndex, int pageSize)
    {
        //logic
    }

我的2条路线是

   routes.MapRoute(
      name: "ShoesA",
      url: "Shoes/{startIndex}",
      defaults: new { startIndex = 0, pageSize = 10, controller = "ShoesConnectors", action = "Index" }
      );

        routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}",
        defaults: new { controller = "Home", action = "Index" }
        );

一切正常。该网址解析为http://localhost:52603/Shoes?SelectedSize=12

我想要的是将URL更改为不使用查询字符串。 EG

http://localhost:52603/Shoes?SelectedSize=12

成为

http://localhost:52603/Shoes/12

(我应该指出,我通过路线使用分页,因此它实际上会显示http://localhost:52603/Shoes/10/12其中10是startIndex)

所以,我添加了以下路线

        routes.MapRoute(
        name: "ShoesB",
        url: "Shoes/{startIndex}/{SelectedSize}/{SelectedColour}",
        defaults: new { startIndex = 0, pageSize = 10, controller = "Shoes", action = "Index" }
        );

        routes.MapRoute(
        name: "ShoesC",
        url: "Shoes/{startIndex}/{SelectedSize}",
        defaults: new { startIndex = 0, pageSize = 10, controller = "Shoes", action = "Index" }
        );

        routes.MapRoute(
        name: "ShoesD",
        url: "Shoes/{startIndex}/{SelectedColour}",
        defaults: new { startIndex = 0, pageSize = 10, controller = "Shoes", action = "Index" }
        );

当我点击我的搜索按钮时,我会看到一个404页面

我知道由于新路线而导致此错误,但我不明白为什么它无法找到该页面...

网址按预期解析为http://localhost:52603/Shoes/0/12,但我不知道如何调试此问题。

为什么MVC找不到正确的控制器?它试图解决什么问题?

2 个答案:

答案 0 :(得分:0)

您想使用Attribute Routing

修改:顺便说一句,如果您可以更新为MVC5,则属性路由“内置”(请参阅​​Attribute Routing in MVC5

答案 1 :(得分:0)

答案是,这在MVC4中很容易完成。我发布的例子非常正确。

错误是在Visual Studio中的项目设置中。我打开了项目的Properites,并导航到Web选项卡。

从这里,我取消了“使用本地IIS Web服务器”并选择“使用Visual Studio开发服务器”,这解决了这个问题。