Switching to {controller}/{id}/{action} breaks RedirectToAction

后端 未结 6 1904
后悔当初
后悔当初 2021-01-04 23:55

I am trying to use proper REST urls with MVC. To do that I switched default Routing from:

{controller}/{action}/{id}
相关标签:
6条回答
  • 2021-01-05 00:23

    Try passing the current route data to methon in your controller action:

    return RedirectToAction("Search", this.RouteData.Values);
    
    0 讨论(0)
  • 2021-01-05 00:32

    When you use RedirectToAction(), internally, MVC will take the existing route data (including the Id value) to build the url. Even if you pass a null RouteValueDictionary, the existing route data will be merged with the new empty route value data.

    The only way around this I can see is to use RedirectToRoute(), as follows:

    return RedirectToRoute("Default", new { controller = "Customer", action = "Search"});
    

    counsellorben

    0 讨论(0)
  • 2021-01-05 00:32

    Remove this part:

    id = UrlParameter.Optional
    

    may be resolve the problem; when you define "id" as an optional parameter, and you have the "Default" map, the "Default" and the "AdminRoute" are same together! regards.

    0 讨论(0)
  • 2021-01-05 00:46

    Try passing in new (empty) RouteValueDictionary in your controller

    return RedirectToAction("Search", new System.Web.Routing.RouteValueDictionary{});
    

    And here:

    Html.ActionLink("Approve", "Approve", new { Id = 23})
    

    I don't even know how can it pick up the Customer controller, since you are not specifying it anywhere. Try providing both controller and action to ActionLink helper.

    0 讨论(0)
  • 2021-01-05 00:46

    I was having a similar problem. Route values that were passed to my controller action were being reused when I tried to redirect the user with RedirectToAction, even if I didn't specify them in the new RouteValueDictionary. The solution that I came up with (after reading counsellorben's post) with was to clear out the RouteData for the current request. That way, I could stop MVC from merging route values that I didn't specify.

    So, in your situation maybe you could do something like this:

    [CustomAuthorize]
    [HttpGet]
    public ActionResult Approve(int id)
    {
        _customerService.Approve(id);
        this.RouteData.Values.Clear();  //clear out current route values
        return RedirectToAction("Search");  //Goes to bad url
    }
    
    0 讨论(0)
  • 2021-01-05 00:48

    I had a similar problem and was able to solve it by adding the id to the default route as well.

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

    If there is truly no id in your default route then you could also try:

    routes.MapRoute(
        "Default", 
        "{controller}/{action}", 
        new { controller = "Home", action = "Index", id = string.Empty });
    
    0 讨论(0)
提交回复
热议问题