C# 在同一控制器上使用两个映射路由时,MVC路由空参数错误
我尝试在我的mvc项目中使用MapRoute,第一条路线“route1”在两个参数下运行良好 现在,第二条路由-在同一个控制器上-recordcontroller-不工作“route2” 并给出了一个错误: 参数字典包含方法“System.Web.Mvc.ActionResult AttachmentDetails(Int32,Int32)”的非null类型“System.Int32”的参数“attId”的null条目 需要帮忙吗C# 在同一控制器上使用两个映射路由时,MVC路由空参数错误,c#,asp.net-mvc,model-view-controller,routing,C#,Asp.net Mvc,Model View Controller,Routing,我尝试在我的mvc项目中使用MapRoute,第一条路线“route1”在两个参数下运行良好 现在,第二条路由-在同一个控制器上-recordcontroller-不工作“route2” 并给出了一个错误: 参数字典包含方法“System.Web.Mvc.ActionResult AttachmentDetails(Int32,Int32)”的非null类型“System.Int32”的参数“attId”的null条目 需要帮忙吗 //route code routes.LowercaseU
//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();
}
当您确实想要匹配
route2
时,您正在匹配route1
要实现此目的,请改用此路由,并将其置于路由1之前
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
。还请注意,我在路由中硬编码了记录
,以确保以记录
开头的URL由路由2
处理,而其他所有由路由1
(或更高的路由)处理,删除id=UrlParameter。如果没有名为id
的参数,则可选择。请查看{controller}/{action}/{libId}/{recordNo}
您说过的“用4个部分匹配我得到的任何URL”。然后你给它传递了一个包含4个部分的URL。所以路由说“亲爱的,我会用那条路由”。这有意义吗?现在,问题是,你不想让它使用那条路线。所以你需要更具体的路线。这就是为什么我使用url:Records
。我说的是“只有当它以记录开头时才匹配此url”。现在,route2
必须在route1
之前,因为它与第一个匹配一起。因此,我们需要确保它匹配route2
,然后它才知道route1
。