当 URL 不包含索引时返回 404
Returning a 404 when the URL does not contain Index
我在 MVC 中遇到路由问题。我已经为我的联系页面创建了一个控制器,但除非我将路由指定为 /contact/index
,否则它将 return 一个 404。我不明白为什么它不能只用 /contact
找到视图在 URL。我的 RouteConfig
看起来不错。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "T",
url: "T/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我能看到它没有找到它的视图的唯一原因是因为我配置了新的路由来显示网站持有页面。有趣的是 /t
确实显示 'demo' 主页,所以我不明白为什么它不喜欢 /contact
。
S.O 文章告诉我,我可以通过给它自己 MapRoute
来解决问题,但我不应该做所有这些吗?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Holding()
{
return View();
}
}
public class ContactController : Controller
{
// GET: Contact
public ActionResult Index()
{
return View();
}
}
这一定很愚蠢,但我无法解决。
您有路由冲突
/contact
将匹配
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
但是由于联系人控制器没有 Holding
操作,您将得到 404 Not Found
并且因为它匹配 Holding 路线,所以它不会继续到下一个 Default 路线,因为第一场比赛获胜。
添加的路由过于笼统,会出现大量错误匹配。
根据显示的控制器,不需要添加路由。保留路径仍将匹配默认路由模板。所以它实际上可以完全删除。
我在 MVC 中遇到路由问题。我已经为我的联系页面创建了一个控制器,但除非我将路由指定为 /contact/index
,否则它将 return 一个 404。我不明白为什么它不能只用 /contact
找到视图在 URL。我的 RouteConfig
看起来不错。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "T",
url: "T/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我能看到它没有找到它的视图的唯一原因是因为我配置了新的路由来显示网站持有页面。有趣的是 /t
确实显示 'demo' 主页,所以我不明白为什么它不喜欢 /contact
。
MapRoute
来解决问题,但我不应该做所有这些吗?
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Holding()
{
return View();
}
}
public class ContactController : Controller
{
// GET: Contact
public ActionResult Index()
{
return View();
}
}
这一定很愚蠢,但我无法解决。
您有路由冲突
/contact
将匹配
routes.MapRoute(
name: "Holding",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Holding", id = UrlParameter.Optional }
);
但是由于联系人控制器没有 Holding
操作,您将得到 404 Not Found
并且因为它匹配 Holding 路线,所以它不会继续到下一个 Default 路线,因为第一场比赛获胜。
添加的路由过于笼统,会出现大量错误匹配。
根据显示的控制器,不需要添加路由。保留路径仍将匹配默认路由模板。所以它实际上可以完全删除。