using mvc route constraints so a url can only be mapped to one of three possible params

FiveTools picture FiveTools · Feb 27, 2012 · Viewed 14.7k times · Source

Here is my route:

routes.MapRoute(null, "myaccount/monitor/{category}", // Matches
                new { controller = "MyAccount", action = "Monitor", category = (string)null }
);

I would like to add a constraint so the category can only match a null or one of three params (i.e. overview, projection, history)

Answer

Gabriele Petrioli picture Gabriele Petrioli · Feb 27, 2012

You can use UrlParameter.Optional to allow nulls, and also use the constraints parameter of the MapRoute method..

 routes.MapRoute(null,
                      "myaccount/monitor/{category}", // Matches
                      new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional  },
                      new { category = "overview|projection|history"}
            );