【问题标题】:MVC routing null parameters error when i use two map-route on the same controller当我在同一控制器上使用两个映射路由时,MVC 路由空参数错误
【发布时间】:2019-06-09 08:59:20
【问题描述】:

我尝试在我的 mvc 项目中使用地图路由,第一个路由“route1”使用两个参数工作正常 http://localhost:43601/records/index/1/5454546

现在第二条路线 - 在同一个控制器上 - 记录控制器 - 不工作“route2” http://localhost:43601/records/attachmentdetails/828/2 并报错:

参数字典包含方法“System.Web.Mvc.ActionResult AttachmentDetails(Int32, Int32)”的不可为空类型“System.Int32”的参数“attId”的空条目

有什么帮助吗?

//route code 
routes.LowercaseUrls = true;
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            //Web API
            routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
            routes.MapRoute(
        name: "route1",
        url: "{controller}/{action}/{libId}/{recordNo}",
        defaults: new { controller = "Records", action = "Index", id = UrlParameter.Optional }
    );
            routes.MapRoute(
           name: "route2",
           url: "{controller}/{action}/{attId}/{atype}",
           defaults: new { controller = "Records", action = "AttachmentDetails", id = UrlParameter.Optional }
       );
                routes.MapRoute(
           name: "Default",
           url: "{controller}/{action}/{id}",
           defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
       );
            routes.MapRoute(
           name: "Default4",
           url: "{controller}/{action}/{attId}/{atype}",
           defaults: new { controller = "FileManager", action = "BookAttachmnt", id = UrlParameter.Optional }
       );
//controllers code
public ActionResult Index(string libId, int recordNo = 0)
        {
}
public ActionResult AttachmentDetails(int attId, int atype)
        {
            BasicSearchAttribute();
            return View();
        }

【问题讨论】:

  • 作为一个附带问题,如果没有名为id 的参数,请删除id = UrlParameter.Optional

标签: c# asp.net-mvc model-view-controller routing


【解决方案1】:

当您真正想要匹配 route2 时,您正在匹配 route1

要实现这一点,请改用此路由,并将其放在之前 route1

routes.MapRoute(
       name: "route2",
       url: "Records/{action}/{attId}/{atype}",
       defaults: new { controller = "Records", action = "AttachmentDetails", id = UrlParameter.Optional }
 );

您的代码不起作用的原因是路由是“自上而下”匹配的(即它们的定义顺序)。您使用的 URL 符合 route1 的规则之前它符合 route2 的规则。唉,route1 有不同的参数名称(libId 而不是attId),因此路由失败,因为您的操作需要attId 参数,但给定 libId 参数。

但是把上面的路由放在前面这意味着它会被使用,而不是route1。另请注意,我在路由中硬编码了Records,以确保以Records 开头的URL 由route2 处理,而其他所有内容route1 处理(或更高版本)路线)。

【讨论】:

  • 看看{controller}/{action}/{libId}/{recordNo} 你说过'匹配我得到的任何 URL 有 4 个部分'。然后你向它传递了一个包含 4 个部分的 URL。所以路由说'很好,我会使用那条路由'。那有意义吗?现在,问题是,您不希望它使用该路由。所以你需要更具体的路线。这就是我使用url: "Records 的原因。我是说'仅匹配此 URL 如果它以 Records 开头'。 现在,route2 需要在之前 route1,因为它与第一个匹配。所以我们需要在它知道route1之前确保它匹配route2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 1970-01-01
相关资源
最近更新 更多