问题
I have a test controller where i have one index action which accept custid
as a argument.
this is how my controller looks
public class TestController : Controller
{
// GET: Test
public ActionResult Index(int custid)
{
return View();
}
}
i have added one extra routing statement in route.config file.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "custom1",
url: "{controller}/{id}",
defaults: new { controller = "Test", action = "Index", custid = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
so when accessing test controller action with url like localhost:50675/test/101 then getting error. error message say
The parameters dictionary contains a null entry for parameter 'custid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'WebAPICRUD.Controllers.TestController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
but when accessing test controller action with url like localhost:50675/test?custid=101 then getting no error.
so i do not understand what mistake is there in code.
What i need to do as a result i can issue this url http://localhost:50675/test/101 which should work. please guide me. thanks
回答1:
Your route definition need to contain a segment for custid
(not id
) to match the name of the parameter. The route definition should also contain the name of the controller to make it unique
routes.MapRoute(
name: "custom1",
url: "Test/{custid}", // modify
defaults: new { controller = "Test", action = "Index"}
);
Note that you can also remove the custid = UrlParameter.Optional
since you do not want it to be optional
来源:https://stackoverflow.com/questions/50581204/asp-net-mvc-routing-issue-which-throwing-exception