Setting an alternate controller folder location in ASP.NET MVC

后端 未结 4 1532
悲&欢浪女
悲&欢浪女 2020-12-30 07:41

We can an MVC app that uses the default folder conventions for the HTML views, but we\'d like to set up alternate \"Services\" folder with controllers used only for web serv

4条回答
  •  自闭症患者
    2020-12-30 08:05

    You can do this using Routing, and keeping the controllers in separate namespaces. MapRoute lets you specify which namespace corresponds to a route.

    Example

    Given this controllers

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

    And the following routing

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

    You should expect the following responses

    /Services/Home

    ServiceController

    /Home

    Controllers

提交回复
热议问题