gpt4 book ai didi

asp.net - 应用程序根的默认路由

转载 作者:行者123 更新时间:2023-12-04 17:45:30 25 4
gpt4 key购买 nike

我怎么能告诉我的mvc -应用程序路由到特定 ControllerAction什么时候没有指定?

调试时http://localhost:54500/应该路由到 http://localhost:54500/Home/Index .

目前我有:

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

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

但这总是抛出

The view 'Index' or its master was not found or no view engine supports the searched locations



编辑 #1

它应该重定向/路由到驻留在 Area 中的 View 。叫 Home .只是想澄清一下,有一个 Controller和一个 Area两者都被命名为 Home .

该区域的配置是:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}

最佳答案

When debugging http://localhost:54500/ should route to http://localhost:54500/Home/Index.



实际上,按照您的配置方式, http://localhost:54500/将路由到 HomeController.Index方法,而不是另一个 URL。

The view 'Index' or its master was not found or no view engine supports the searched locations



此错误表示路由成功,但 Controller 返回了不存在的 View 的路径。

由于您还提到您正在使用区域并发布了您的配置,因此很清楚发生了什么。您的配置按以下顺序运行:
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}

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

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

所以,如果你传递 URL http://localhost:54500/ ,Area 路由将错过(因为它不以 /Home 开头)并且它将匹配 Root路线。此 Root路线不会路由到您的区域。有 2 种方法可以解决此问题。

选项 1 - 将根路由添加到归属区域
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Root",
"",
new { controller = "Home", action = "Index" }
);

context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}

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

选项 2 - 设置 DataToken 以指示归属区域
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"Home_default",
"Home/{controller}/{action}/{id}",
new {action = "Index", id = UrlParameter.Optional}
);
}

routes.MapRoute(
name: "Root",
url: "",
defaults: new { controller = "Home", action = "Index" }
).DataTokens["area"] = "Home";

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

关于asp.net - 应用程序根的默认路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com