首页 > 解决方案 > 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应该可以工作。请指导我。谢谢

标签: asp.net-mvc-5

解决方案


您的路由定义需要包含一个段 for custid(not id) 以匹配参数的名称。路由定义还应包含控制器的名称以使其唯一

routes.MapRoute(
    name: "custom1",
    url: "Test/{custid}", // modify
    defaults: new { controller = "Test", action = "Index"}
);

请注意,您也可以删除,custid = UrlParameter.Optional因为您不希望它是可选的


推荐阅读