Mvc区域路由?

时间:2013-03-25 13:32:54

标签: asp.net-mvc url-routing area

区域文件夹如下所示:

Areas 
    Admin
        Controllers
            UserController
            BranchController
            AdminHomeController

项目目录如下:

Controller
    UserController
        GetAllUsers

区域路线注册

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

项目路线注册

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new string[] { "MyApp.Areas.Admin.Controllers" });
}

当我像这样路由时:http://mydomain.com/User/GetAllUsers我得到资源未找到错误(404)。将UserController添加到Area后,我收到此错误。

如何修复此错误?

谢谢...

2 个答案:

答案 0 :(得分:28)

您搞砸了控制器名称空间。

您的主要路线定义应为:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    namespaces: new string[] { "MyApp.Controllers" }
);

您的管理区域路线注册应为:

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional },
        new { controller = "Branch|AdminHome|User" },
        new[] { "MyApp.Areas.Admin.Controllers" }
    );
}

请注意应该如何使用正确的命名空间。

答案 1 :(得分:0)

ASP.NET Core MVC的最新解决方案。

[Area("Products")]
public class HomeController : Controller

来源:https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/areas