繁体   English   中英

在ASP.NET MVC中使用Session还是2 TempData哪个更好?

[英]Which is better, Session or 2 TempData in ASP.NET MVC?

我发现在这里这里和其他地方,我不应该在ASP MVC中大量使用Session

因此,我想知道使用TempData像下面那样更好。

public ActionResult Action1()
{
  if (SomeCondition)
  {
     /*
       I want to show alert to user based on this value that should appear in Action2 view
       So, is it better to:
       1. Session["user"] = "something";
       2. TempData["user"] = "something";
     */
     return RedirectToAction("Action2");
  }
     return View();
}

public ActionResult Action2()
{
   /*
      1. I can read Session["user"] in the view
      2. TempData["user"] = TempData["user"].ToString();
         Now I can read TempData in the view
   */
   return View();
}

TempData是默认情况下使用Session的提供程序。 但是,可以将其更改为基于cookie的提供程序。

唯一真正的区别是TempData仅存储数据,直到再次读取为止;在此, Session将存储数据,直到超时到期为止。

没有完美的解决方案来存储请求之间的数据。 如果可能,应避免使用它。 在MVC中,您可以通过将数据加载到View中并将ViewModel回到控制器ViewModel轻松地做到这一点,在控制器上您可以再次读取数据。

另外,请参阅“三思而后行”,以了解使用会话状态的某些可能替代会话状态的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM