How do I change the order of routes.MapRoute in MV

2019-05-31 01:42发布

问题:

How do I change the order of the url parameter when registering routes in global.asax.cs?

I registered the route like so: (Note: I also have the default MVC3 route registered as well)

routes.MapRoute(
  "SurveyWizard",
  "survey/{id}/{action}",
  new { id = UrlParameter.Optional, action = "AddQuestions" });

My controller:

public ActionResult AddQuestions(int id)
{
  if(id < 1 || id == null)
    //Redirect somewhere  
  var survey = _surveyService.GetSurveyById(id);
  //other controller logic
  return View(survey);
}

When I type the url .../survey/1/AddQuestions the resource can't be found. When I run a route debugger the route shows as valid.

Is this even possible in MVC3? I know in Restful WCF, you can structure routes like this no problem. In the grand scheme of things I could probably live with {controller}/{action}/{id}, but I believe in using verbs only when necessary and in my case the correct url should be structured per my example above.

Any ideas? Thanks.

回答1:

Your route is missing a default controller, like:

routes.MapRoute(
  "SurveyWizard",
  "survey/{id}/{action}",
  new { controller="Survey", action="AddQuestions" });

Another point you should be aware of is that the default rote should be the last one...