【问题标题】:ASP.Net MVC: Routing issue which throwing exceptionASP.Net MVC:引发异常的路由问题
【发布时间】:2018-05-29 09:44:27
【问题描述】:

我有一个测试控制器,其中我有一个接受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 访问测试控制器操作时,会出现错误。错误信息说

参数字典包含参数“custid”的空条目 方法的不可为空类型“System.Int32” 'System.Web.Mvc.ActionResult 索引(Int32)' 在 'WebAPICRUD.Controllers.TestController'。可选参数必须是 引用类型,可为空的类型,或被声明为可选 范围。参数名称:参数

但是当使用 localhost:50675/test?custid=101 之类的 url 访问测试控制器操作时,不会出现错误。

所以我不明白代码中有什么错误。

我需要做的结果是我可以发出这个 url http://localhost:50675/test/101 应该可以工作。请指导我。谢谢

【问题讨论】:

    标签: asp.net-mvc-5


    【解决方案1】:

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

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

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

    【讨论】:

    • 抱歉,这是一个错字,非常严重的错误。谢谢先生。
    • 先生的解决方案不起作用。请在您身边创建一个控制器,该控制器将具有一个带有一个 custid 参数的索引操作,并在路由配置文件中进行必要的更改,然后运行....必须看到解决方案不起作用。我根据您的解释进行了更改,但现在当我发出此 url localhost:50675/test?101 时出现错误“HTTP 404。您正在寻找的资源(或其依赖项之一)可能已被删除,名称已更改,或者暂时不可用。请检查以下 URL 并确保其拼写正确。"
    • 我给出的代码可以正常工作(我不知道你还犯了什么错误)
    • 和它的url localhost:50675/test/101匹配路由(不是test?101
    • 对不起,我的结果有误。现在一切正常
    猜你喜欢
    • 2012-10-06
    • 2011-10-07
    • 1970-01-01
    • 2013-11-13
    • 2011-11-30
    • 2013-06-07
    • 1970-01-01
    相关资源
    最近更新 更多