Setting an alternate controller folder location in

2020-02-25 08:46发布

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 services returning xml or json.

So the route "/Services/Tasks/List" would be routed to "/Services/TaskService.cs", while "/Tasks/List" would be routed to the standard "/Controllers/TaskController.cs"

We'd like to keep the service controllers separate from the view controllers. We don't think areas or using another project will work. What would be the best way to approach this?

3条回答
SAY GOODBYE
2楼-- · 2020-02-25 09:03

You'll want to create your own controller factory implementing IControllerFactory.

Check out http://nayyeri.net/custom-controller-factory-in-asp-net-mvc for an example.

查看更多
小情绪 Triste *
3楼-- · 2020-02-25 09: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

查看更多
太酷不给撩
4楼-- · 2020-02-25 09:06

If you see yellow folder names Add folder Name in root

After, you have to modify routes.MapRoute into "App_Start > RouteConfig"

Modify Default route

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

and Add this

routes.MapRoute(
       "ApiControllerOne", // Name of folder
       "ApiControllerOne/{controller}/{action}/{id}",
        new { controller = "ApiFactory", action = "callFactoryOne", id = UrlParameter.Optional },
        new string[] { "mvcPartialView.ApiControllerOne" } // Namespace
    );
查看更多
登录 后发表回答