asp.net-mvc-5 - ASP.Net MVC:引发异常的路由问题
问题描述
我有一个测试控制器,其中我有一个接受custid
作为参数的索引操作。
这就是我的控制器的外观
public class TestController : Controller
{
// GET: Test
public ActionResult Index(int custid)
{
return View();
}
}
我在 route.config 文件中添加了一个额外的路由语句。
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "custom1",
url: "{controller}/{id}",
defaults: new { controller = "Test", action = "Index", custid = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
因此,当使用localhost:50675/test/101 之类的 url 访问测试控制器操作时,会出现错误。错误信息说
参数字典包含“WebAPICRUD.Controllers.TestController”中方法“System.Web.Mvc.ActionResult Index(Int32)”的不可空类型“System.Int32”的参数“custid”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。参数名称:参数
但是当使用localhost:50675/test?custid=101 之类的 url 访问测试控制器操作时,不会出现错误。
所以我不明白代码中有什么错误。
我需要做的结果是我可以发出这个 URL http://localhost:50675/test/101应该可以工作。请指导我。谢谢
解决方案
您的路由定义需要包含一个段 for custid
(not id
) 以匹配参数的名称。路由定义还应包含控制器的名称以使其唯一
routes.MapRoute(
name: "custom1",
url: "Test/{custid}", // modify
defaults: new { controller = "Test", action = "Index"}
);
请注意,您也可以删除,custid = UrlParameter.Optional
因为您不希望它是可选的
推荐阅读
- php - cURL Laravel 和 Aspx 端点
- node.js - 在 MongoDB 中聚合双嵌套数组的文档
- c# - checkip.dyndns.org 服务返回 LAN IP
- jquery - 使用 <输入> 的 jQuery UI 可排序位置
- python - Python - 重塑嵌套数组
- c# - 带有子路由的 ASP.NET MVC 路由,没有属性路由
- angular - Angular Material Datatable 未对来自 Http 请求的数据进行排序
- sql - 数据透视表获取多个值
- python - 如何识别带有队列的 Python 线程是否已完成任务?
- c++ - Googletest:值参数化类型测试