C# 如何成功编写MVC路由定义

C# 如何成功编写MVC路由定义,c#,asp.net-mvc,routes,asp.net-mvc-routing,C#,Asp.net Mvc,Routes,Asp.net Mvc Routing,有人能帮我找出问题所在,并向我解释控制器是如何知道应该使用哪个路由定义的(因为在很多情况下,URI可以容纳多个路由定义) 这是我的问题 控制器方法: [HttpGet] public ActionResult PreencherFormulario(int idPacientePesquisa, int idFormularioPesquisa) 路由(所有在Global.asax上定义的路由): 网址: http://localhost:61404/RealizacaoPesquisa/P

有人能帮我找出问题所在,并向我解释控制器是如何知道应该使用哪个路由定义的(因为在很多情况下,URI可以容纳多个路由定义)

这是我的问题

控制器方法:

[HttpGet]
public ActionResult PreencherFormulario(int idPacientePesquisa, int idFormularioPesquisa) 
路由(所有在Global.asax上定义的路由):

网址:

http://localhost:61404/RealizacaoPesquisa/PreencherFormulario/1/1
错误:

The parameters dictionary contains a null entry for parameter 'idPacientePesquisa' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult PreencherFormulario(Int32, Int32)' in 'Prometheus.Controllers.RealizacaoPesquisaController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Nome do parâmetro: parameters

您的问题在于以下路由的默认值为null,并且由于该路由位于您怀疑的路由之前,因此routeurl的格式与下一个路由的格式相同。此路由会被考虑,并且在路由时失败,因为您的操作参数是不可为null的int

  RouteTable.Routes.MapRoute(
        "ParticipacaoPesquisa",
        "{controller}/{action}/{idPesquisa}/{nrProntuario}",
        null, /*<--- This is the culprit*/
        new { idPesquisa = @"\d+" }
  );
因此,它然后尝试使用参数
idPesquisa
调用您的操作,该参数在该路径中映射


但是您的操作需要一些其他的参数名,并且它们也不可为空,因此如果失败。

首先,您要编写从更具体到更一般的路由。它使用它匹配的第一个

因此,您的问题是您的路由与此路由匹配,并且您正在将idPacientPesqusa设置为null

 RouteTable.Routes.MapRoute(
        "ParticipacaoPesquisa",
        "{controller}/{action}/{idPesquisa}/{nrProntuario}",
        null, <-- here!!
        new { idPesquisa = @"\d+" }
     );

好吧,我现在明白了。。。但是,即使我描述了一些默认设置,我也无法理解这会有什么帮助——因为两个URL都是完整的(所有部分都存在),默认设置并不重要,对吗?@MarceloMyara的问题是路由的顺序。由于该路由模式也与您的url模式相匹配,并且它位于预期路由之前,因此它采用第一个路由。这就是为什么建议将默认路线移至底部。试着在底部放置更多的通用路线,在上面放置特定路线。贾里德,是的,我想到过类似的事情。不幸的是,它不起作用。我只是想,要使其工作,我必须为“controller”和“action”指定一个默认值,否则我会收到一个错误,说URL模式中缺少action或controller单词。@MarceloMyara啊,是的。请原谅我的复制粘贴错误。我已经更新了我的答案。
"{controller}/{action}/{idPesquisa}/{nrProntuario}",
 RouteTable.Routes.MapRoute(
        "ParticipacaoPesquisa",
        "{controller}/{action}/{idPesquisa}/{nrProntuario}",
        null, <-- here!!
        new { idPesquisa = @"\d+" }
     );
 RouteTable.Routes.MapRoute(
        name: "PreencherForm",
        url:"RealizacaoPesquisa/PreencherFormulario/{idPacientePesquisa}/{idFormularioPesquisa}",
        defaults: new { controller = "RealizacaoPesquisa", action = "PreencherFormulario", idPacientePesquisa = 1, idFormularioPesquisa = 1 },
        constraints: new { idPacientePesquisa = @"\d+", idFormularioPesquisa = @"\d+" }
     );