繁体   English   中英

ASP.NET MVC路由问题中的约束

[英]Constraints in ASP.NET MVC route issue

我试图从这个网站创建一个例子。

他们定义了一条路线:

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
);

它的工作意味着The resource could not be foundproductId没有整数值时会发生错误。 (我访问http://website.com/product/1a然后显示错误,否则将显示视图)

但是如果我将url格式从route更改为:

"Product/{action}/{productId}"

并访问它: http//website.com/Product/Details/1a ,然后发生错误,如: The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method

那么,为什么不显示The resource could not be found错误? 为什么在我施加约束路线时达到了行动?

PS:我改变了路由的url格式,现在它看起来像:

routes.MapRoute(
    "Product",
    "Product/{action}/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
);

原因不是您指定的路由,而是代码中的另一个路由项,很可能是默认的MVC路由:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

productId的值与约束不匹配时,路由引擎继续检查下一个映射。 然后它匹配最后一个,但是当试图调用您的方法时,模型绑定器不能将字符串1a转换为int ,这实际上意味着缺少productId参数。

为什么错误The resource could not be found

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
);

当url是http://website.com/product/1a

答:你得到的错误是因为当你对url的路由应用约束时,如果约束不匹配MVC只是拒绝该请求..这是你得到资源错误的唯一原因。


为什么错误The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method

routes.MapRoute(
    "Product",
    "Product/{action}/{productId}",
    new {controller="Product", action="Details"}
);

当url http://website.com/Product/Details/1a

答案:在这种情况下,没有应用ModelBinder ,因此ModelBinder尝试使用DefaultValuProvider匹配参数,如果它无法将值与参数匹配,那么当它到达此处时会抛出错误,因为没有转换意味着null。

为避免此错误,您可以尝试此操作

一个。 将defualt值传递给action方法

  public ActionResult Index(int id=0)

使用可空参数创建方法,因此null得到自动处理

  public ActionResult Index(int? id)

问题不在于约束路线

routes.MapRoute(
    "Product",
    "Product/{productId}",
    new {controller="Product", action="Details"},
    new {productId = @"\d+" }
);

按照上面的代码,你正在寻找整数的产品ID,所以如果你提供像http://website.com/Product/Details/1a这样的字符串,它会尝试将第一个值与第一个页面持有者匹配,这意味着产品与productId相匹配在这种情况下...为了匹配这个mvc使用ModuleBinder当模块绑定器找到它的string而不是int即无法在int转换string时它会引发你得到的错误。

因此,根据您的路线,它将Details与产品ID匹配,但无法找到1a匹配,这是您找不到资源的原因。


如果你有像这样的Product/{action}/{productId}这样的路线并且像这样调用网址http://website.com/Product/Details/1a它将{action}1a{ProductId} Details匹配,而不是错误The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM