路线 URL 必须以 '/' 开头

Route URL must be started with '/'

我已经在家庭控制器中声明了 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" }
    );

语法无效:

The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.

如果我删除第二个配置,

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

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

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

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

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();
}