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

Jason Underhill picture Jason Underhill · Aug 4, 2011 · Viewed 57.7k times · Source

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.`

Answer

Hector Correa picture Hector Correa · Aug 4, 2011

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.