在ASP.NET MVC区域路由中找不到错误404

How*_*amp 9 asp.net asp.net-mvc asp.net-mvc-routing

我在MVC 5中遇到了一个区域路由问题.当我浏览/ Evernote/EvernoteAuth时,我得到404资源无法找到错误.

我的区域看起来像这样:

Areas
    Evernote
        Controllers
            EvernoteAuthController
        Views
            EvernoteAuth
                Index.cshtml
Run Code Online (Sandbox Code Playgroud)

EvernoteAreaRegistration.cs(UPDATE:RegisterArea()没有被调用,所以我做了一个Clean和Rebuild.现在它被调用但结果相同.)包含这个路由映射:

public override void RegisterArea(AreaRegistrationContext context)
{
     context.MapRoute(
        "Evernote_default",
        "Evernote/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
     );
}
Run Code Online (Sandbox Code Playgroud)

EvernoteAuthController的Index()方法只返回View().

我的应用程序的RouteConfig.cs目前没有定义路由映射,但我尝试通过实现这个手动"强制"它:

routes.MapRoute(
    name: "EvernoteAuthorization",
    url: "Evernote/{controller}/{action}",
    defaults: new { controller = "EvernoteAuth", action = "Index", id = UrlParameter.Optional },
    namespaces: new string[] { "AysncOAuth.Evernote.Simple.SampleMVC.Controllers" }
);
Run Code Online (Sandbox Code Playgroud)

但无论此路线图是存在还是已注释掉,我都会得到相同的结果.

使用Phil Haack的asp.net mvc路由调试器,我看到我的路由匹配正常,区域名称,控制器名称和Action方法名称匹配.我在控制器操作方法中放置了断点,并且从未输入过这些方法.更新:浏览/ Evernote/EvernoteAuth时从未输入这些方法,但是当我浏览区域名称/ Evernote时,实例化了EvernoteAuthController并调用了Index()方法.(为什么那个控制器被/ Evernote实例化而不是/ Evernote/EvernoteAuth?)然后我收到了错误:

The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/EvernoteAuth/Index.aspx
~/Views/EvernoteAuth/Index.ascx
~/Views/Shared/Index.aspx
~/Views/Shared/Index.ascx
~/Views/EvernoteAuth/Index.cshtml
~/Views/Shared/Index.cshtml
and so on...
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我相信〜= /(应用程序根目录).因此该区域Areas\Evernote\Views未被搜索.

我该如何解决这个问题?

Dav*_*eDM 22

向控制器添加正确的命名空间非常重要

  namespace YourDefaultNamespace.Areas.Evernote.Controllers
  {
    public class EvernoteAuthController : Controller
    { 
        ...
        ...
    }
  }
Run Code Online (Sandbox Code Playgroud)

因此路由可以找到您的控制器.现在,您必须使用该方法在Global.asax.cs中注册该区域

AreaRegistration.RegisterAllAreas();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢; 从导致我的错误的其他项目复制现有控制器时.命名空间很重要,需要正确. (3认同)

Iva*_*van 5

小心使用AreaRegistration.RegisterAllAreas();内部Application_Start方法。

如果你把它放在AreaRegistration.RegisterAllAreas()最后一个里面Application_Start,那是行不通的。

AreaRegistration.RegisterAllAreas()是第一个将成功执行路由..

例子:

 protected void Application_Start(object sender, EventArgs e)
 {
        AreaRegistration.RegisterAllAreas();  //<--- Here work

        FilterConfig.Configure(GlobalFilters.Filters);
        RouteConfig.Configure(RouteTable.Routes);

        AreaRegistration.RegisterAllAreas();  //<--- Here not work
 }
Run Code Online (Sandbox Code Playgroud)