AspNetCore MVC - return RedirectToAction被忽略了

5

我有一个以下的操作:

[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");
  • SendEmailVerificationCode 带有 HttpPost 属性;我将其改为 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"); 但是它没有起作用。 - Chakian
1个回答

6

我通过在应用程序中添加一些日志记录来解决了问题。结果发现,实际问题被隐藏了。

我使用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());


1
看到这种问题,我感到非常痛心,因为它的原因完全是隐藏且无关的。这是现代微软产品的另一个基本问题。这种情况变得越来越普遍。 - EthR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接