Reputation: 135
I have a custom route registered in my application, but only the default route is working correctly.
Here are my route mappings:
routes.MapRoute(
name: "MyCustomRoute",
url: "Foo/Index/{myid}",
defaults: new { controller = "Foo", action = "Index", myid = UrlParameter.Optional },
namespaces: new[] { "MyApp.Controllers" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyApp.Controllers" }
);
And my FooController action method
public ActionResult Index(int MyID)
{
//...
return View();
}
If I add the myid parameter to the querystring things work fine (i.e. /Foo/Index/?myid=1). But the rewritten url (/Foo/Index/1) results in this error:
The parameters dictionary contains a null entry for parameter 'MyID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'TPC_CS_Portal.Controllers.FooController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
As mentioned, my other controllers that use the default route (with id parameter) all work fine (e.g. /SomethingElse/Index/1).
What do I need to do to get my custom route working?
Upvotes: 0
Views: 43
Reputation: 135
The problem here was that there was a separate MapRoute defined elsewhere against the FooController:
routes.MapRoute(
name: "MyOtherCustomRoute",
url: "Foo/Index/{param1}/{param2}",
defaults: new { controller = "Foo", action = "Index", param1 = UrlParameter.Optional, param2 = UrlParameter.Optional },
namespaces: new[] { "MyApp.Controllers" }
);
This was taking precedence (matching against the requested url), so I moved things around so that it appears after MyCustomRoute.
Upvotes: 1