Search code examples
asp.net-mvcroutesasp.net-mvc-routing

How do I route a URL with a querystring in ASP.NET MVC?


I'm trying to setup a custom route in MVC to take a URL from another system in the following format:

../ABC/ABC01?Key=123&Group=456

The 01 after the second ABC is a step number this will change and the Key and Group parameters will change. I need to route this to one action in a controller with the step number key and group as paramters. I've attempted the following code however it throws an exception:

Code:

routes.MapRoute(
    "OpenCase", 
    "ABC/ABC{stepNo}?Key={key}&Group={group}",
    new {controller = "ABC1", action = "OpenCase"}
);

Exception:

`The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.`

Solution

  • You cannot include the query string in the route. Try with a route like this:

    routes.MapRoute("OpenCase", "ABC/ABC{stepNo}",
       new { controller = "ABC1", action = "OpenCase" });
    

    Then, on your controller add a method like this:

    public class ABC1 : Controller
    {
        public ActionResult OpenCase(string stepno, string key, string group)
        {
            // do stuff here
            return View();
        }        
    }
    

    ASP.NET MVC will automatically map the query string parameters to the parameters in the method in the controller.