【问题标题】:Route URL must be started with '/'路由 URL 必须以“/”开头
【发布时间】:2016-04-05 02:27:02
【问题描述】:

我已经在 Home 控制器中声明了 Index 操作:

[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" }
    );

语法无效:

路由 URL 不能以 '/' 或 '~' 字符开头,也不能 包含一个“?”字符。

如果我删除第二个配置,

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

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

我的问题是:有没有办法配置以“/”开头的路由 URL(无控制器,无操作)?

【问题讨论】:

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


【解决方案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();
}

【讨论】:

  • 很抱歉,但当我调用/?type=promotion 时,URL 确实以“/”开头,如您在上面看到的。我不知道url: ""。这很有帮助
猜你喜欢
  • 2018-09-22
  • 2017-06-09
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 2017-03-19
  • 2020-02-15
相关资源
最近更新 更多