ASP.. NET MVC路由:类似子文件夹的路由

本文关键字:路由 文件夹 NET MVC ASP | 更新日期: 2023-09-27 18:17:54

这是我在ASP中的文件结构。. NET MVC 4项目,关于控制器:

 |--Models
 |--Controllers
       |
       |--api
       |   |
       |   |--UsersController.cs  (MyProject.Controllers.API.UsersController.cs)
       |   |--PlacesController.cs (MyProject.Controllers.API.PlacesController.cs)
       |
       |--UsersController.cs  (MyProject.Controllers.ViewsControllers.UsersController.cs)
       |--PlacesController.cs  (MyProject.Controllers.ViewsControllers.PlacesController.cs)

命名空间MyProject.Controllers.API下的控制器都返回JsonResult
命名空间MyProject.Controllers.ViewsControllers下的控制器都返回Views

我的RouteConfig.cs如下:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/",
            defaults: new { controller = "Places", action = "List" },
            namespaces: new[] { "MyProject.Controllers.ViewsControllers" }
        );
    }

当我使用web浏览器到http://localhost/Places/List时,它返回视图,正如预期的那样,因为它使用控制器MyProject.Controllers.PlacesControlller.cs

我如何为我的json控制器创建一个MapRoute,以便当我使用web浏览器到http://localhost/api/Places/SomeAction时,它使用MyProject.Controllers.API.PlacesController.cs类?

注意:我不想使用ASP。. NET MVC的api特性

我试过这个,但是它不工作:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "ViewRoute",
            url: "{controller}/{action}/",
            namespaces: new[] { "MyProject.Controllers.ViewsControllers" }
        );
        routes.MapRoute(
            name: "APIRoute",
            url: "api/{controller}/{action}/",
            namespaces: new[] { "MyProject.Controllers.API" }
        );
    }

ASP.. NET MVC路由:类似子文件夹的路由

要调用正常的控制器动作,你必须像这样注册你的路由,你已经这样做了:

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
        name: "ViewRoute",
        url: "{controller}/{action}/",
        namespaces: new[] { "MyProject.Controllers.ViewsControllers" }
    );

对于调用api控制器,在你的路由类中定义以下方法,并在你的全局中注册这个方法。asax Application_Start()方法:

    public static void RegisterAPI(HttpConfiguration config)
    {
        // Web API configuration and services
        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }