本文介绍了切换到{controller}/{id}/{action}会中断RedirectToAction的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对MVC使用正确的REST网址.为此,我从以下位置切换了默认路由:

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

{controller}/{action}/{id}

{controller}/{id}/{action}

所以而不是:

/Customer/Approve/23

现在有

/Customer/23/Approve

ActionLink似乎可以正常运行,但是在CustomerController中使用以下代码:

ActionLink seems to work ok, but the following code in CustomerController:

[CustomAuthorize]
[HttpGet]
public ActionResult Approve(int id)
{
    _customerService.Approve(id);
    return RedirectToAction("Search");  //Goes to bad url
}

出现在URL /Customer/23/Search上.虽然应该去/Customer/Search.它以某种方式记住了23 (id).

ends up on url /Customer/23/Search. While it should be going to /Customer/Search. Somehow it remembers 23 (id).

这是我在global.cs中的路由代码

Here is my routing code in global.cs

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

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

如果我同时切换两个功能,则RedirectToAction开始工作,但是使用:

If I switch the two functions, RedirectToAction starts working, but using:

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

现在生成/Customer/Approve?id=23,而不是/Customer/23/Approve.

我可以指定直接网址,例如~/Customer/23/Approve,而不是使用ActionLinkRedirectToAction,但是宁愿坚持使用MVC提供的功能.

I could specify direct urls like ~/Customer/23/Approve, instead of using ActionLink and RedirectToAction, but would rather stick to functions provided by MVC.

推荐答案

当您使用RedirectToAction()时,MVC会在内部使用现有的路由数据(包括ID值)来构建网址.即使您传递一个空的RouteValueDictionary,现有的路由数据也将与新的空路由值数据合并.

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.

解决此问题的唯一方法是使用RedirectToRoute(),如下所示:

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

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

counsellorben

counsellorben

这篇关于切换到{controller}/{id}/{action}会中断RedirectToAction的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:11