简体   繁体   中英

.Net MVC routing producing a circular route

I have a website that we have recently made some changes to, and this seems to have broken some of my routing.

the initial issue was that I was getting a 405 verb not allowed when using the following form.

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

this was constructing a URL such that it was seen in the html as Recommendations/ , leaving Index out (presumably because it was a default parameter. However the index method signature was changed, so it took an optional parameter, which appeared to be causing the issue.

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

To fix this, I added the following to my route.config file

    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 }
      );

But this has now had the side effect of intercepting any calls to other methods within the RecommendationsController, and redirecting me back to the index page ie Recommendations/index

So how do I change my routing config, so that

recommendations/ and recommendations/enquiryId=1 map to recommendations/index but Recommendations/<other method> goes to Recommendations/<other method> ?

Is enquiryId an int I assume? If so, you can constrain your route to only look for integers.

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

this will match /Recommendations/123 but not /Recommendations/MyCustomAction

Routes are greedy by default and will try to match all possible values before falling through to the next one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM