【问题标题】:Value of TempData becomes null after "Redirect"“重定向”后 TempData 的值变为空
【发布时间】:2021-10-06 22:03:02
【问题描述】:

我在 Redirect 后遇到了 TempData 问题。

public ActionResult LoginCredentials()
{
    // Calling "SetError()" in catch(), if password mismatch.                        
    try{}

    catch()
    {
      return SetError();
    }   
}

public ActionResult SetError()
{
    // set the value of TempData as "true"                        
    TempData["error"] = true;
    return Redirect("/Login");                
}


public ActionResult Index()
{
    ViewData["useError"]= TempData["error"]; // at this point TempData["error"] is null.
    ...
}

在SetError()中TempData的值成功设置为真,“重定向”后出现问题,值变为“空”,我不能再使用了。

【问题讨论】:

  • 请在此处发布您的控制器类代码...
  • 无论我有什么我都发布了。
  • (Index) 函数中的 TempData["error"] 将为空,因为 (SetError) 函数未执行。
  • 很难理解你想在这里做什么。应该是return RedirectToAction("SetError); 而不是return SetError();,但是该方法所做的只是再次重定向,那么为什么不在LoginCredentials() 方法中只使用catch() { TempData["error"] = true; return RedirectToAction("Index); } 呢?
  • @user3106445 我尝试完全按照您的做法做,对我来说效果很好,问题可能是别的。

标签: c# asp.net-mvc


【解决方案1】:
  1. 可能浏览器没有 cookie
  2. TempDataDictionary 对象中的数据仅从一个请求持续到下一个请求,除非您使用 Keep 方法标记一个或多个要保留的键,根据您的代码,如果您重定向到登录页面,然后重定向到索引,该值将为空。您只能在登录页面阅读。

【讨论】:

  • 我用过一次 TempData,index 就是控制器的视图。
  • @user3106445 TempData:表示仅从一个请求持续到下一个请求的一组数据。 msdn.microsoft.com/en-us/library/… 重定向到登录是第一个请求,从登录重定向到索引是第二个请求
  • 我已经标记了这个答案,因为现在我已经直接重定向到索引页面了。
  • 那么即使从未读取过 TempData 仍然会变为 null 吗?
  • 在 web.config 中启用时,我正在使用 http 访问网站。
【解决方案2】:
    services.Configure<CookiePolicyOptions>(options =>
    {
                    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                    //options.CheckConsentNeeded = context => true;
                    options.MinimumSameSitePolicy = SameSiteMode.None;
    });

turn off options.CheckConsentNeeded = context => true; 

这对我有用

【讨论】:

    【解决方案3】:

    我发现 .Net Core 非常有问题。 我必须在配置中关闭它

    options.CheckConsentNeeded = context => true;
    

    当我使用重定向导航到另一个页面时它起作用了。

    但是,在刷新页面时,TempDate 或 ViewData 会失去其价值。但是当我在“视图”中将它重新分配给它自己时,它起作用了:

    @{
    TempData["somevalue"] = TempData["somevalue"];
    
    }
    

    【讨论】:

      【解决方案4】:

      使用 RedirectToAction

      public ActionResult SetError()
      {
      // set the value of TempData as "true"                        
         TempData["error"] = true;
         return RedirectToAction("YourViewName");                
       }
      

      【讨论】:

      • 使用RedirectToAction时也是null
      【解决方案5】:

      据我了解ViewData 仅在重定向后保存数据,而不是在另一个 Http 请求发生时保存数据。所以在Login 方法内(你重定向到的地方)这个ViewData["useError"] 必须可用,但是Index 方法只是在另一个http 请求期间执行的另一种方法。这就是为什么ViewData["useError"] 是空的
      如果要在不同的 Http 请求之间存储数据,可以使用 Session

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-03
        • 2019-06-15
        • 2017-03-31
        • 2016-06-20
        相关资源
        最近更新 更多