【问题标题】:AspNetCore MVC - return RedirectToAction is getting ignoredAspNetCore MVC - 返回 RedirectToAction 被忽略
【发布时间】:2016-12-24 23:53:11
【问题描述】:

我有一个动作如下:

[HttpGet]
public IActionResult SendEmailVerificationCode(int userId)
{
    SpaceUser user = userManager.FindByIdAsync(userId).Result;
    bool taskComleted = SendEmailVerificationLink(userId).IsCompleted;
    if (taskComleted)
    {
        AddToErrorData(InfoMessages.EmailVerificationLinkSent_Params, user.Email);
        return RedirectToAction(nameof(HomeController.Index), "Home");
    }
    else
    {
        return RedirectToAction("EmailNotConfirmed", new { userId = user.Id });
    }
}

当我让代码跳转到 else 块(调试时)时,它会重定向到同一控制器中的 EmailNotConfirmed 操作。但它不会重定向到HomeControllerIndex 操作。相反,浏览器停留在Account/SendEmailVerificationCode 并显示一个空白页面。

HomeController.Index如下:

[HttpGet]
public IActionResult Index()
{
    return View();
}

我试过这些:

  • 一开始SendEmailVerificationCode 操作是异步的,但HomeController.Index 不是。所以我将它们都声明为异步的。
  • 然后我从他们两个中删除了async 声明。
  • 我试过return RedirectToAction("Index", "Home");
  • SendEmailVerificationCodeHttpPost 属性;我把它改成了HttpGet

如何重定向到不同控制器中的操作?
任何帮助将不胜感激。

P.S.:我已经对这个问题进行了一段时间的研究,并且我已经阅读了以下问题的解决方案:
MVC RedirectToAction is not working properly
RedirectToAction gets ignored

但是这些或关于在 ajax 请求后未重定向操作的问题都没有帮助我。

谢谢。

【问题讨论】:

  • 尝试在Startup.cs 中添加一条新路由为routes.MapRoute("MainIndex", "{controller}/{action}", new { controller = "Home", action = "Index" }); 并通过:return RedirectToRoute("MainIndex"); 进行重定向,但没有成功。

标签: c# asp.net-core-mvc


【解决方案1】:

我通过在应用程序中添加一些日志来解决问题。事实证明,真正的问题被隐藏了。

我使用 TempData 来存储自定义错误消息,并通过我在问题中显示的 AddToErrorData 函数使用它。

在 AspNetCore 中,Serializable 属性与ISerializable 接口一起消失了。因此,TempData 无法序列化我的自定义 IList 对象列表。

当我将TempData[ConstantParameters.ErrorData] = _errorData; 更改为TempData[ConstantParameters.ErrorData] = JsonConvert.SerializeObject(_errorData); 时,重定向问题就解决了。

供参考:我还必须将 TempData 检索行更改为:_errorData = JsonConvert.DeserializeObject<ErrorDataList>(TempData[ConstantParameters.ErrorData].ToString());

【讨论】:

  • 看到这种类型的问题让我很痛苦,而且原因完全隐藏且不相关。现代 Microsoft 产品的另一个基本问题。它们变得太常见了。
猜你喜欢
  • 2016-03-19
  • 2021-01-13
  • 2018-08-07
  • 2021-10-03
  • 1970-01-01
  • 2020-03-23
  • 2021-01-31
  • 2014-09-03
  • 2020-11-01
相关资源
最近更新 更多