MVC4 Default route when using areas

2020-05-21 04:34发布

I'm trying to use areas within MVC app, I would like that the default route will be resolved to the HomeController within the admin area but it resolves to the home controller in root site. I added the namespace of the admin HomeController but it still resolved to the root HomeController.

My Route config:

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

        );
    }
}

admin area route

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 - Admin area

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

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

   }
}

Any idea why it wouldn't resolve properly? Thanks

8条回答
地球回转人心会变
2楼-- · 2020-05-21 05:22

In your

RouteConfig.cs

routes.MapRoute("redirect all other requests", "{*url}",
        new {
            controller = "UnderConstruction",
            action = "Index"
            }).DataTokens = new RouteValueDictionary(new { area = "Shop" });
查看更多
欢心
3楼-- · 2020-05-21 05:23

I've tested your code for the area registration and it works and selects the right controller. However, the view resolution finds the view in the root folder, even if the right controller is used.

To test, I used the following home index action in my areas home controller:

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

Then my index.chstml in /Views/Home:

Root View: @Model

and my index.cshtml in /Areas/Admin/Views/Home:

Admin Area view: @Model

When run, the output is:

Root View: Admin area home controller

So the route makes the home controller in the admin area run, but then thew view resolution goes on and finds the root view instead of the admin view.

So in the end, it is indeed the view selection that is wrong, so your problem is the same as in How to set a Default Route (To an Area) in MVC.

查看更多
登录 后发表回答