ASP.Net MVC: Routing issue which throwing exception

廉价感情. 提交于 2021-02-10 16:11:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!