C# 使用TempData、Session或静态变量在同一控制器中的ActionResults之间共享相同的值是否更好?
我有一个MVC控制器,我希望将相同的(静态)信息传递给相同的控制器中的任何ActionResult,只能由同一用户在索引页中的新选择进行更改。我读到过,使用静态变量被认为是不好的做法。我的站点在Intranet环境中使用Windows身份验证,在任何时间最多可以有10个人查看任何一个页面。如果我理解正确,静态变量可能会被页面用户以外的其他人覆盖,只需在同一时间查看同一页面 作为替代,我阅读了关于“TempData”和“Session Variables”的文章,但到目前为止,我还没有读到任何东西表明这些方法是否可以确保只有查看页面实例的人才能在索引页面中设置变量。我在下面粘贴了一些代码示例,它们展示了我的意思。我已经让它们工作了,我的问题是哪种方法确保只有查看该页面实例的人才能设置和读取值 此代码示例显示控制器级静态变量的使用:C# 使用TempData、Session或静态变量在同一控制器中的ActionResults之间共享相同的值是否更好?,c#,asp.net-mvc,C#,Asp.net Mvc,我有一个MVC控制器,我希望将相同的(静态)信息传递给相同的控制器中的任何ActionResult,只能由同一用户在索引页中的新选择进行更改。我读到过,使用静态变量被认为是不好的做法。我的站点在Intranet环境中使用Windows身份验证,在任何时间最多可以有10个人查看任何一个页面。如果我理解正确,静态变量可能会被页面用户以外的其他人覆盖,只需在同一时间查看同一页面 作为替代,我阅读了关于“TempData”和“Session Variables”的文章,但到目前为止,我还没有读到任何东西
public class HomeController : Controller
{
public static string _currentChoice;
public ActionResult Index(string CurrentChoice)
{
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
ViewBag.Message = "Your choice is " + _currentChoice;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your choice is still "+_currentChoice;
return View();
}
}
此代码示例使用TempData和Session:
public class HomeController : Controller
{
public ActionResult Index(string CurrentChoice)
{
var _currentChoice = CurrentChoice;
_currentChoice = string.IsNullOrEmpty(CurrentChoice)?"nothing":CurrentChoice;
TempData["CurrentChoice"] = _currentChoice;
Session["SessionChoice"] = _currentChoice;
ViewBag.Message = "Your choice is " + _currentChoice;
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your choice is still " + TempData["CurrentChoice"]
+ "\nYour Session choice is " + Session["SessionChoice"];
return View();
}
}
您将要使用该会话。您提供的每个选项都有不同的用例:
- 静态变量对类的每个实例使用相同的变量。这意味着每个用户都会看到相同的值,如果一个用户更改变量,那么其他所有用户的变量都会更改。因为您希望每个用户都是唯一的,所以这不是一个选项
- TempData用于在重定向期间传递数据,根据
- 会话数据用于存储当前会话的数据,并且每个用户都是唯一的