Search code examples
c#.netasp.net-mvcasp.net-mvc-routing

MVC Route match based on parameter type


I have a situation where I want the ThisAction controller to look like this :

public ActionResult Index()...
public ActionResult Index(int programId)...
public ActionResult Index(string programKey)...

With the goal of a route being set up like so

www.website.com/ThisAction/ <- matches first function
www.website.com/ThisAction/123 <- matches second function
www.website.com/ThisAction/ABC <- matches third function

Is this possible to set up in the global.asx route?


Solution

  • You would need to use attribute routing with route constraints to easily get that flexibility.

    [RoutePrefix("ThisAction")]
    public class ThisActionController : Controller {
        [HttpGet]
        [Route("")] //Matches GET ThisAction
        public ActionResult Index() {
            //...
        }
        [HttpGet]
        [Route("{programId:int}")] //Matches GET ThisAction/123
        public ActionResult Index(int programId) {
            //...
        }
        [HttpGet]
        [Route("{programKey}")] //Matches GET ThisAction/ABC
        public ActionResult Index(string programKey) {
            //...
        }    
    }
    

    Make sure that attribute routeing is enabled in RouteConfig

    public class RouteConfig {
        public static void RegisterRoutes(RouteCollection routes) {
            //...other code removed for brevity
    
            //Attribute routes
            routes.MapMvcAttributeRoutes();
    
            //convention-based routes
    
            //...other code removed for brevity
    
            routes.MapRoute(
                "Default",
                "{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = "" }
            );
        }
    }
    

    The route will work along side convention-based routing.

    Just note that once you use it on a controller you have to use it on the entire controller. So the controller is either all convention-based or all attribute routing.