簡體   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