“重定向”后TempData的值变为null

时间:2015-07-27 11:06:24

标签: c# asp.net-mvc

我在重定向后面临 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的值成功设置为true,问题发生在“Redirect”之后,值变为“null”,我不能再使用它了。

5 个答案:

答案 0 :(得分:4)

  1. 也许浏览器是无cookie的
  2. TempDataDictionary对象中的数据仅保留从一个请求到下一个请求,除非您使用Keep方法标记一个或多个要保留的键,根据您的代码,如果您重定向到登录页面,然后重定向到索引,该值将为null。你只能在登录页面阅读。

答案 1 :(得分:1)

  

使用RedirectToAction

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

答案 2 :(得分:1)

    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 :(得分:0)

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

答案 4 :(得分:0)

我发现.Net Core令人难以置信。 我必须在“配置”中将其关闭

options.CheckConsentNeeded = context => true;

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

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

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

}