Asp.net-Mvc-4

使用區域時的 MVC4 預設路由

  • September 21, 2017

我正在嘗試使用 MVC 應用程序中的區域,我希望預設路由將解析為管理區域中的 HomeController,但它解析為根站點中的主控制器。我添加了管理員 HomeController 的命名空間,但它仍然解析為根 HomeController。

我的路線配置:

public class RouteConfig
{
   public static void RegisterRoutes(RouteCollection routes)
   {
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

       routes.MapRoute(
           "Default",
           "{controller}/{action}/{id}",
           new {controller = "Home", action = "Index", id = UrlParameter.Optional },
           new[] {"MvcApplicationAreas.Areas.Admin.Controllers"}

       );
   }
}

管理區域路線

public class AdminAreaRegistration : AreaRegistration
{
   public override string AreaName
   {
       get
       {
           return "Admin";
       }
   }

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

HomeController - 管理區域

namespace MvcApplicationAreas.Areas.Admin.Controllers
{
  public class HomeController : Controller
  {

      public ActionResult Index()
      {
          return View();
      }

  }
}

知道為什麼它不能正確解決嗎?謝謝

我已經測試了您的區域註冊程式碼,它可以工作並選擇正確的控制器。但是,即使使用了正確的控制器,視圖解析也會在根文件夾中找到視圖。

為了測試,我在我的區域家庭控制器中使用了以下家庭索引操作:

public ActionResult Index()
{
   return View(model: "Admin area home controller");
}

然後我在 /Views/Home 中的 index.chstml:

Root View: @Model

和我在 /Areas/Admin/Views/Home 中的 index.cshtml:

Admin Area view: @Model

執行時,輸出為:

根視圖:管理區域主控制器

因此該路由使管理區域中的主控制器執行,但隨後視圖解析繼續並找到根視圖而不是管理視圖。

所以最後,確實是視圖選擇錯誤,所以你的問題和How to set a Default Route (To an Area) in MVC 中的問題一樣。

最直接的方法是將數據令牌添加到您的預設路由:

routes.MapRoute(
   "Default",
   "{controller}/{action}/{id}",
   new {controller = "Home", action = "Index", id = UrlParameter.Optional }
).DataTokens.Add("area", "Admin");

只需添加

.DataTokens.Add("area", "[your area name]");

到預設路由定義的末尾。

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