简体   繁体   English

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

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

I found that I shouldn't use Session a lot in ASP MVC here , here and in other places. 我发现在这里这里和其他地方,我不应该在ASP MVC中大量使用Session

So, I want to know if it's better to use TempData like I did below or not. 因此,我想知道使用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 is a provider that uses Session by default. TempData是默认情况下使用Session的提供程序。 It can be changed to be a cookie-based provider, though. 但是,可以将其更改为基于cookie的提供程序。

The only real difference is that TempData stores the data only until it is read again, where Session will store the data until a timeout expires. 唯一真正的区别是TempData仅存储数据,直到再次读取为止;在此, Session将存储数据,直到超时到期为止。

There is no perfect solution for storing data between requests. 没有完美的解决方案来存储请求之间的数据。 When possible, you should avoid it. 如果可能,应避免使用它。 In MVC you can do this fairly easily by loading the data into the View and posting the ViewModel back to the controller where you can read the data again. 在MVC中,您可以通过将数据加载到View中并将ViewModel回到控制器ViewModel轻松地做到这一点,在控制器上您可以再次读取数据。

Also, see Think twice about using session state for some possible alternatives to session state. 另外,请参阅“三思而后行”,以了解使用会话状态的某些可能替代会话状态的方法。

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

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