【问题标题】:.Net MVC routing producing a circular route.Net MVC 路由产生循环路由
【发布时间】:2023-04-03 01:25:01
【问题描述】:

我有一个网站,我们最近对它进行了一些更改,这似乎破坏了我的一些路由。

最初的问题是我在使用以下表格时收到了 405 动词不允许。

using (@Html.BeginForm("Index", "Recommendations", FormMethod.Post))
{
  <button class="btn btn-large btn-primary"  d="btnNext">@ViewBag.TextDisplay</button>        
}

这是在构造一个 URL,使其在 html 中显示为 Recommendations/,而将 Index 排除在外(可能是因为它是默认参数。但是 index 方法签名已更改,因此它采用了一个可选参数,它出现导致问题。

   [HttpPost]
    public async Task<ActionResult> Index(int? enquiryId)

为了解决这个问题,我在我的 route.config 文件中添加了以下内容

    routes.MapRoute(
          name: "DefaultWithIndex",
          url: "Recommendations/{enquiryId}",
          defaults: new { controller = "Recommendations", action = "Index", enquiryId= UrlParameter.Optional });

        routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );

但这现在已经产生了拦截对 RecommendationsController 中其他方法的任何调用的副作用,并将我重定向回索引页面,即Recommendations/index

那么我该如何更改我的路由配置,以便

recommendations/recommendations/enquiryId=1 映射到 recommendations/indexRecommendations/&lt;other method&gt; 转到 Recommendations/&lt;other method&gt;

【问题讨论】:

    标签: c# asp.net-mvc routing


    【解决方案1】:

    enquiryId 是我假设的 int 吗?如果是这样,您可以将路由限制为仅查找整数。

    routes.MapRoute(
          name: "DefaultWithIndex",
          url: "Recommendations/{enquiryId}",
          defaults: new { controller = "Recommendations", action = "Index", enquiryId= UrlParameter.Optional },
          constraints: new {enquiryId= @"\d+" }); //restrict enquiryId to one or more integers
    

    这将匹配 /Recommendations/123 但不匹配 /Recommendations/MyCustomAction

    默认情况下,路由是贪婪的,并且会在进入下一个之前尝试匹配所有可能的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 1970-01-01
      • 2018-08-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-12
      相关资源
      最近更新 更多