asp.net-mvc MVC区域路由?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15616240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:41:10  来源:igfitidea点击:

Mvc area routing?

asp.net-mvcurl-routingarea

提问by AliR?za Ad?yah?i

Area folders look like :

区域文件夹看起来像:

Areas 
    Admin
        Controllers
            UserController
            BranchController
            AdminHomeController

Project directories look like :

项目目录如下所示:

Controller
    UserController
        GetAllUsers

area route registration

区域路线登记

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

project route registration

项目路线登记

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

When I route like this: http://mydomain.com/User/GetAllUsersI get resource not found error (404). I get this error after adding UserController to Area.

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

How can I fix this error?

我该如何解决这个错误?

Thanks...

谢谢...

回答by Darin Dimitrov

You've messed up your controller namespaces.

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

Your main route definition should be:

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

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

And your Admin area route registration should be:

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

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

Notice how the correct namespaces should be used.

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

回答by Mark

An up to date solution for ASP.NET Core MVC.

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

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

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

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