我们可以使用对HTML View 使用默认文件夹约定的MVC应用程序,但我们希望使用仅用于返回xml或json的Web服务的 Controller 来设置备用“Services”文件夹。
因此,路由“/Services/Tasks/List”将被路由到“/Services/TaskService.cs”,而“/Tasks/List”将被路由到标准“/Controllers/TaskController.cs”
我们希望将服务 Controller 与 View Controller 分开。我们认为无法使用区域或使用其他项目。解决这个问题的最佳方法是什么?
最佳答案
您可以使用“路由”将 Controller 保持在单独的命名空间中。
MapRoute允许您指定与路由对应的 namespace 。
示例
给定这个 Controller
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");
}
}
}
和以下路由
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
);
您应该期待以下回应
/服务/首页
/家