asp.net-coreasp.net-core-mvcasp.net-core-2.0asp.net-core-mvc-2.0asp.net-core-routing

Can I override the default action for a single controller in ASP.Net Core MVC


Is it possible to override the default action for a single controller without affecting the rest of the routing? I currently have a default route of

routes.MapRoute(
    name: "Default",
    template: "{controller}/{action}",
    defaults: new { controller = "Book", action = "Index" }
);

This works in the general case but I now want to add an AdminController, but I want the default action on AdminController to be Users, instead of Index.

I don't really want to use attribute routing on this controller as we may later update the default routing and I want to keep as much as possible centralised and DRY. I just want the urls /Admin and /Admin/Users to route to the Users action in this one controller.

I'm currently using ASP.Net Core 2.0 with the intention to move to 2.1 as soon as it is released. It's currently running on .Net Framework but we want to upgrade to .Net Core as soon as we can get rid of some dependencies we currently have on the framework (unlikely to be for the first release).

Any suggestions?


Solution

  • While more intensive than using attribute routing you can do

    routes.MapRoute( 
        name: "AdminDefault", 
        template: "Admin/{action}", 
        defaults: new { controller = "Admin", action = "Users" }
    );
    
    routes.MapRoute(
        name: "Default",
        template: "{controller=Book}/{action=Index}",        
    );
    

    using Attribute routing on the controller it would have been

    [Route("[controller]")]
    public class AdminController : Controller {    
        [HttpGet]
        [Route("")]             //Match GET admin
        [Route("[action]")]     //Match Get admin/users
        public IActionResult Users() {
            return View();    
        }    
    }
    

    Or even

    [Route("[controller]/{action=Users}")]
    public class AdminController : Controller {    
        [HttpGet]
        public IActionResult Users() {
            return View();    
        }    
    }
    

    Reference Routing to Controller Actions in ASP.NET Core