【问题标题】:Why am I getting 'The parameters dictionary contains a null entry for parameter' for my custom MapRoute为什么我的自定义 MapRoute 会出现“参数字典包含参数的空条目”
【发布时间】:2019-09-15 23:48:35
【问题描述】:

我在我的应用程序中注册了一个自定义路由,但只有默认路由正常工作。

这是我的路线图:

        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" }
        );

还有我的 FooController 操作方法

 public ActionResult Index(int MyID)
    {
        //...
   return View();
    }

如果我将 myid 参数添加到查询字符串中,则一切正常(即 /Foo/Index/?myid=1)。但是重写的 url (/Foo/Index/1) 会导致这个错误:

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

如前所述,我的其他使用默认路由(带有 id 参数)的控制器都可以正常工作(例如 /SomethingElse/Index/1)。

我需要做什么才能使我的自定义路线正常工作?

【问题讨论】:

    标签: c# asp.net-mvc-5 routes


    【解决方案1】:

    这里的问题是在其他地方针对 FooController 定义了一个单独的 MapRoute:

    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" }
        );
    

    这是优先的(与请求的 url 匹配),所以我移动了一些东西,以便它出现在 MyCustomRoute 之后。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      相关资源
      最近更新 更多