Asp.net

在 ASP.NET MVC 區域路由中找不到錯誤 404

  • December 21, 2021

我在 MVC 5 中遇到區域路由問題。當我瀏覽到 /Evernote/EvernoteAuth 時,我收到 404 資源找不到錯誤。

我的區域是這樣的:

Areas
   Evernote
       Controllers
           EvernoteAuthController
       Views
           EvernoteAuth
               Index.cshtml

EvernoteAreaRegistration.cs(更新:RegisterArea() 沒有被呼叫,所以我進行了清理和重建。現在它被呼叫但結果相同。)包含此路線圖:

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

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

但無論此路線圖是否存在或被註釋掉,我都會得到相同的結果。

使用 Phil Haack 的asp.net mvc 路由調試器,我看到我的路由匹配得很好,並且區域名稱、控制器名稱和操作方法名稱匹配。我在控制器操作方法中放置了斷點,而這些方法從未輸入過。更新:瀏覽/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...

在這種情況下,我相信〜= /(應用程序根)。所以該區域Areas\Evernote\Views沒有被搜尋。

我該如何解決這個問題?

向控制器添加正確的命名空間很重要

 namespace YourDefaultNamespace.Areas.Evernote.Controllers
 {
   public class EvernoteAuthController : Controller
   { 
       ...
       ...
   }
 }

所以路由可以找到你的控制器。現在您必須使用該方法在 Global.asax.cs 中註冊該區域

AreaRegistration.RegisterAllAreas();

小心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
}

引用自:https://stackoverflow.com/questions/25450549