路线网址必须以' /'

时间:2015-12-31 04:21:07

标签: c# asp.net-mvc routes url-routing asp.net-mvc-routing

我已在家庭控制器中声明了索引操作:

[HttpGet]
public ActionResult Index(string type)
{
   if (string.IsNullOrEmpty(type))
   {
      return RedirectToAction("Index", new { type = "promotion" });
   }
   return View();
}

接受:

https://localhost:44300/home/index?type=promotion

https://localhost:44300/?type=promotion

在为404页面配置路由之前一切正常:

    routes.MapRoute(
        name: "homepage",
        url: "home/index",
        defaults: new { controller = "Home", action = "Index" }
    );
    routes.MapRoute(
        name: "default",
        url: "/",
        defaults: new { controller = "Home", action = "Index" }
    );
    routes.MapRoute(
        "404-PageNotFound",
        "{*url}",
        new { controller = "Error", action = "PageNotFound" }
    );

语法无效:

  

路线网址不能以' /'或者'〜'性格,它不能   包含'?'字符。

如果删除第二个配置,

https://localhost:44300/?type=promotion

不会被接受。 - >显示404页面。

我的问题是:有没有办法用' /'配置路由网址开头? (无控制器,无动作)?

1 个答案:

答案 0 :(得分:1)

您的路由配置错误,因为错误表明它不能以/开头,而且对于主页不需要。在这种情况下,它应该是一个空字符串。

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

然而,想要将多个路线映射到网站的主页,这有点不寻常(而不是SEO友好)。

重定向到主页也很常见,主页会在网络上进行额外的往返。通常直接路由到您想要的页面就足够了,没有这种不必要的往返。

routes.MapRoute(
    name: "homepage",
    url: "home/index",
    defaults: new { controller = "Home", action = "Index", type = "promotion" }
);
routes.MapRoute(
    name: "default",
    url: "/",
    defaults: new { controller = "Home", action = "Index", type = "promotion" }
);

// and your action...
[HttpGet]
public ActionResult Index(string type)
{
   return View();
}