ASP.NET MVC应用启动报404错误,默认路由配置排查求助
我的ASP.NET MVC应用目录结构按Check-in、Arrivals、Departures三大模块划分,Models、Controllers、Views均遵循此层级。希望应用启动后直接进入Departures模块的WIP页面,但启动时出现以下404错误:
Server Error in '/' Application.
The resource cannot be found.Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
我在router.config文件中配置的默认路由如下:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Departures/MasterWip", action = "Index", id = UrlParameter.Optional } );
Controllers/Departures/MasterWipController.cs中的Index方法代码:
public ActionResult Index() { IRepositoryFactory repoFactory = new RepositoryFactory(); IMasterWipRepository wipRepo = repoFactory.GetMasterWipRepo(); model = wipRepo.GetAllByNLIDate(new DateTime(2022, 1, 14)); ViewBag.Model = model; return View("~/Views/Departures/MasterWip"); }
请问哪里配置有误或遗漏?
路由控制器名称格式错误:ASP.NET MVC路由不支持控制器名称中包含斜杠(
Departures/MasterWip),斜杠会被解析为URL路径分段,系统会尝试寻找名为Departures的控制器,而非Departures文件夹下的MasterWipController。正确的控制器名称应仅写类名(去掉Controller后缀),即MasterWip。修正路由配置:将默认路由的
controller默认值改为MasterWip,修改后的路由代码:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "MasterWip", action = "Index", id = UrlParameter.Optional } );
视图路径验证:确保
~/Views/Departures/MasterWip.cshtml文件存在;若想遵循MVC默认视图匹配规则,可将视图移至~/Views/MasterWip/Index.cshtml,此时只需return View();即可自动找到视图,无需指定完整路径。补充:若使用区域(Area)结构:如果计划将Departures作为独立区域,需先创建Area(系统会自动生成
AreaRegistration类),再配置区域路由,示例如下:
routes.MapRoute( name: "Departures_default", url: "Departures/{controller}/{action}/{id}", defaults: new { controller = "MasterWip", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "你的应用命名空间.Areas.Departures.Controllers" } );
同时需保证控制器位于Areas/Departures/Controllers目录,视图位于Areas/Departures/Views目录。
内容的提问来源于stack exchange,提问作者Doug Gardiner

