【问题标题】:Redirect to Action in another controller重定向到另一个控制器中的操作
【发布时间】:2012-05-28 13:11:40
【问题描述】:

我有两个控制器,都称为AccountController。其中一个,我们称之为Controller A,在Area 中,称为Admin,另一个,我们称之为Controller B,不在任何Area 中(我猜这意味着它在默认的@987654328 中@?)。 Controller B 有一个名为 Loginaction method。我在Controller A 中有一个action method,其中有这一行

return RedirectToAction("LogIn", "Account");

问题是当这条线被执行时我得到一个404,因为试图重定向到Controller A中不存在的action。我想在Controller B 中拨打action method。这可能吗?

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3 c#-4.0 redirecttoaction


【解决方案1】:

您可以在routeValues 参数中提供area。试试这个:

return RedirectToAction("LogIn", "Account", new { area = "Admin" });

或者

return RedirectToAction("LogIn", "Account", new { area = "" });

取决于您的目标区域。

【讨论】:

  • 如果我想从某个区域的视图转到不在任何区域的控制器的操作怎么办。与 MVC5 中一样,右上角的注销按钮位于 AccountController 中,它不位于任何区域。我想从某个区域的视图中注销???
  • 我的第二个例子,area = "",会为你做这件事。
  • 这对我来说适用于 ASP.NET Core....当我升级到最新版本时,RedirectToAction 坏了,我使用 area = "" 和一个空字符串让它工作。跨度>
【解决方案2】:

使用这个:

return RedirectToAction("LogIn", "Account", new { area = "" });

这将重定向到“全局”区域中Account 控制器中的LogIn 操作。

它正在使用这个RedirectToAction重载:

protected internal RedirectToRouteResult RedirectToAction(
    string actionName,
    string controllerName,
    Object routeValues
)

MSDN

【讨论】:

    【解决方案3】:

    你可以用这个:

    return RedirectToAction("actionName", "controllerName", new { area = "Admin" });
    

    【讨论】:

      【解决方案4】:

      使用这个:

          return this.RedirectToAction<AccountController>(m => m.LogIn());
      

      【讨论】:

      • 我喜欢这个概念。我一直讨厌 RedirectToAction 的字符串部分,认为它应该更像你输入的内容,但这似乎激怒了 c#。这是在 4.6.2 之后的框架中吗?
      • @user3071434 不,您可以使用添加“使用 Microsoft.Web.Mvc”。您可以避免字符串部分并减少由于错误的操作文本而导致运行时出错
      【解决方案5】:

      RedirectToRoute() 也可用。此外,更好的方法可能是使用 nameof(),这样您就可以避免在代码库中硬编码字符串。

      return RedirectToRoute(nameof(AccountController) + nameof(AccountController.Login));
      

      而且,如果您要重定向到带有参数的端点,请传递这些参数。

      return RedirectToRoute(nameof(Account) + nameof(Account.ChangePassword), new { id = id });
      

      【讨论】:

      • 我注意到使用这种方法的一个警告是,您将创建一个新请求,该请求将通过路由引擎向下传递,然后到达控制器。如果您进行多个间接操作,与 RedirectToAction 相比,响应可能会更慢
      【解决方案6】:

      尝试切换它们:

      return RedirectToAction("Account", "Login");
      

      我试过了,效果很好。

      【讨论】:

        【解决方案7】:

        这应该可以工作

        return RedirectToAction("actionName", "controllerName", null);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-31
          • 1970-01-01
          • 1970-01-01
          • 2012-05-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多