gpt4 book ai didi

asp.net-mvc - ASP.NET MVC路由冲突-输入变量为空值

转载 作者:行者123 更新时间:2023-12-04 04:25:09 25 4
gpt4 key购买 nike

我不知道为什么我的路线会发生冲突。我的Global.asax文件中有这些文件:

        routes.MapRoute(
"CustomerView", "{controller}/{action}/{username}",
new { controller = "Home", action = "Index", username = "" }
);

routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "0" }
);

到目前为止,一切工作正常,除非我像这样创建了 Controller Action :
    public ActionResult MyAction(int id)
{
//Do stuff here
return View();
}

当我尝试通过 http://mydomain/MyController/MyAction/5查看它时,我得到:

Server Error in '/' Application.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Track(Int32)' in 'InTouch.Controllers.OrderController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters



向我暗示 id值未正确读取。当然enoguh,当我交换周围路线的顺序时,它工作正常。到目前为止,我的理解(被认为是有限的)是,如果路由中指定的变量名与 Controller Action 定义中指定的变量名匹配,则它将假定该变量名与顺序无关。显然我错了。交换订单会导致其他 Controller 操作中断。在这种情况下处理路线的正确方法是什么?

最佳答案

您的示例的问题在于,匹配发生在第一条路线上,并且用户名参数显示为“5”。您可以使用约束来限制每个参数可接受的值以完成所需的操作。由于接受ID的“默认”路由比“CustomerView”路由更具限制性,因此我将首先列出对“Id”参数具有约束的“默认”路由:

routes.MapRoute(
"Default", "{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "0" },
new { id = @"\d+" }
);

如果Id为整数值,这将导致第一条路线仅匹配。然后,所有其他请求都将落入“CustomerView”路由,该路由将提取没有整数作为该第三个参数的任何其他请求。

请查看 Creating a Route Constraint以获取约束说明。

关于asp.net-mvc - ASP.NET MVC路由冲突-输入变量为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com