是什么导致浏览器URL行在MVC4 asp.net中填充Route

时间:2013-04-19 18:32:09

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

当我去我的主页时

http://localhost:5119/  

重定向到

http://localhost:5119/Home

(这是我的浏览器网址栏中显示的内容,我希望它不显示/ Home)

我知道这是我的默认路由,但我无法弄清楚是什么导致我的URL行被重写在浏览器中。转到基本URL时,Visual Studio 2012中的默认示例没有此问题。我正在附上我的路线调试图片(这似乎对我没有帮助,但可能有一些价值)。

谢谢,-Peter

添加此后。它是路线代码的相关部分

        // HOME
        int currentYearInt;
        Int32.TryParse(currentYear, out currentYearInt);
        routes.MapRoute("HomeRouteAll", "Home/{yearInt}",
                  new
                  {
                      /* Your default route */
                      controller = "Home",
                      action = "Index"
                  });



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

enter image description here

1 个答案:

答案 0 :(得分:1)

您看到的是因为默认路由上方的路由Home/{year}具有{year}参数的默认值。

路由引擎做出以下决定:

  1. 从路线列表顶部开始
  2. 寻找与您的路线值匹配的内容(controller =“Home”,Action =“Index”)。
  3. 在第一场比赛中,返回,这是您的网址。
  4. 由于您有匹配的控制器(Home)和action(Index)以及 year参数的默认值,因此路由引擎与路由Home/{year}匹配,因此提供网址http://domain.com/Home

    快速修复将是a)使年份没有默认值(Home/2013),b)将任何结果移动到不同的控制器(NewName/{year}),c)将其移动到不同的操作(NewIndex/{year})或d)更新您的默认路由以使用year参数而不是id

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

    修改

    我不确定你的路线定义中的tryParse内容是什么,但在我的测试中,这似乎完成了你想要做的事情:

    routes.MapRoute(
                    name: "Test",
                    url: "Home/{year}",
                    defaults: new { controller = "Home", action = "Index"}, 
    //this line causes the year to be an integer
    constraints: new { year = @"\d+" }
                    );
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
    

    行为:

    http://domain.com/ - >调用Home控制器,年份参数为null值的索引操作(不重定向到Home / 2013)

    http://domain.com/Home/2010 - >调用Home Controller,使用2010年的索引操作参数

    http://domain.com/Home/ - > call Home Controller,年度值为null的索引操作。

    如果您在两条路线中的第一条路线中定义了默认年份,那么转到http://domain.com/Home将调用本地控制器,2013年的索引操作,并且仍然不会发生重定向。

    最后,我怀疑您的主页/索引操作看起来像这样:

    public ActionResult Index(int year){...}
    

    如果当您点击Home / Index操作时,您希望自动填充2013,则将int更改为可为空的参数,并在那里而不是您的路线进行。

    public ActionResult Index(int? year){
        if(!year.hasValue){
            year = 2013;
        }
    

    通过在此处执行此逻辑而不是路由,您应该阻止重定向到Home /,因为您没有匹配的{year}参数。