【问题标题】:c# MVC custom Route not matchingc#MVC自定义路由不匹配
【发布时间】:2014-08-13 16:06:57
【问题描述】:

我在 MVC5 中的默认路由之前定义了一个自定义路由,但由于某种原因它没有被命中。它到达了默认路由。

我的路线定义如下:

        routes.MapRoute(
            name: "PDF Viewer",
            url : "pdf/{id}",
            defaults : new { controller = "PdfViewer", action = "Index", id = UrlParameter.Optional },
            namespaces : new[] { "App.Web.Controllers" }
        );
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults : new { controller = "Calendar", action = "Index", id = UrlParameter.Optional },
            namespaces : new[] { "App.Web.Controllers" }
        );

当导航到/pdf/1 时,它不会被路线捕获。 Route Debugger 显示如下结果:

【问题讨论】:

  • 当你尝试/PdfViewer/Index/1?
  • 好的,好主意。使用该 URL 时,它仍然返回服务器错误,但是当我调试时,我的 HandleError 属性或 Global.asax Application_Error 事件中没有任何错误
  • 是 404(未找到)还是 500(服务器错误)?
  • @haim770 哈!不知道发生了什么,可能是缓存问题,但我清除了浏览器缓存并再次尝试,然后它实际上在 Global.asax 中发现了错误。这是错误"The current request for action 'Index' on controller type 'PdfViewerController' is ambiguous between the following action methods: App.Web.Controllers.PdfViewerController.Index() and App.Web.Controllers.PdfViewerController.Index(Int32)"。我不明白,我在网址中传递了Int32
  • 传递给Index(int32 ...)的参数的名称是什么?

标签: c# asp.net-mvc routes asp.net-mvc-5 routedebugger


【解决方案1】:

从“PDF 查看器”路由默认值中删除 id = UrlParameters.Optional

id 是可选的时,框架会认为请求不明确,因为它可以同时匹配Index()Index(int id)

【讨论】:

  • 但是我希望 url /pdf 转到 Index() 操作,或者我应该只有一个带有可选 int? id 参数的操作
猜你喜欢
  • 2014-01-08
  • 1970-01-01
  • 2016-04-29
  • 2013-07-15
  • 1970-01-01
  • 2018-11-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多