在ASP.NET MVC中设置备用控制器文件夹位置

Ste*_*ols 12 asp.net-mvc asp.net-mvc-routing asp.net-mvc-controller

我们可以使用HTML视图的默认文件夹约定的MVC应用程序,但是我们想要设置备用"服务"文件夹,其中控制器仅用于返回xml或json的Web服务.

因此路由"/ Services/Tasks/List"将路由到"/Services/TaskService.cs",而"/ Tasks/List"将路由到标准"/Controllers/TaskController.cs"

我们希望将服务控制器与视图控制器分开.我们认为区域或使用其他项目不会起作用.什么是最好的方法来解决这个问题?

CGK*_*CGK 11

您可以使用"路由"执行此操作,并将控制器保留在单独的命名空间中.MapRoute允许您指定与路由对应的命名空间.

鉴于此控制器

namespace CustomControllerFactory.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("Controllers");
        }
    }
}

namespace CustomControllerFactory.ServiceControllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
           return new ContentResult("ServiceControllers");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以及路由

 routes.MapRoute(
           "Services",
           "Services/{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.ServiceControllers" } // Namespace
        );


        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "CustomControllerFactory.Controllers"} // Namespace
        );
Run Code Online (Sandbox Code Playgroud)

您应该期待以下回复

/服务/主页

的ServiceController

/家

控制器