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

时间:2014-08-12 19:00:20

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing maproute

这是我的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" }
        );
    }

当我使用网络浏览器访问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" }
        );
    }

1 个答案:

答案 0 :(得分:1)

要调用正常的控制器操作,您必须注册您已经完成的路线:

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

对于调用api控制器,在路由类中定义以下方法,并在global.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 }
        );
    }