I have add a new route in a default mvc project like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name:"test",
url:"{controller}/{userId}/{action}/{cardId}",
defaults: new {controller="User", userId=UrlParameter.Optional, action="card", cardId=UrlParameter.Optional }
);
And I have a action method like this(with a controller name as "user"):
public ActionResult card(string userId, string cardId="")
{
if (string.IsNullOrEmpty(cardId))
{
return Json(new[]{
new {id=456, number="1234", name="ayj"},
new {id=123, number="2345", name="xxx"}
}, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { id = 123, number = "2345", name = "xxx" }, JsonRequestBehavior.AllowGet);
}
}
When I visit /user/1/card/2
, it returns the correct json, however when I visit /user/1/card
, I expect it to return an array, but it turns out to return a 404 error
. Any one could help me?
I think when you use the URL without
cardId
, route engine is using your default route, therefore 404, move your custom route above the default route.