MVC区域的路由?(Mvc area routing?)

2019-07-23 06:14发布

区域的文件夹的样子:

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的区域后,出现此错误。

如何解决这个问题?

谢谢...

Answer 1:

你搞砸了你的控制器命名空间。

你的主要路线定义应该是:

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

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



Answer 2:

一个最新的解决方案为ASP.NET MVC的核心。

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

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



文章来源: Mvc area routing?