在 HttpContext.Current.Items 与 ViewData 中存储数据
什么时候适合在 HttpContext.Current.Items[...]
中存储数据,什么时候适合在 ViewData[...]
中存储数据?
我正在尝试找出在此集合中存储数据的最佳实践,但不确定在 HttpContext.Current.Items
中存储用户特定的数据是否安全。
一种用例是从基本控制器的 OnActionExecuting(...)
传递用户积分,以用于 Controller
计算并在 Views
中显示>;我知道我应该使用 ViewData
来实现此目的,但我得到了一些与嵌套部分视图不一致的结果。
说 HttpContext.Current.Items[...]
与 Controllers
类似 Controllers
是否正确? strong>ViewData[...]
是 Views 吗?
When is it appropriate to store data in HttpContext.Current.Items[...]
vs storing data in ViewData[...]
?
I'm trying to figure out the best practices for storing data in this collection and I'm not sure if it's safe to store user-specific data in HttpContext.Current.Items
.
One use-case is passing down user credits from a base controller's OnActionExecuting(...)
to be used in Controller
calculations and for display in Views
; I know I should be using ViewData
for this, but I've had some inconsistent results with nested partial views.
Would it be correct to say that HttpContext.Current.Items[...]
is to Controllers
like ViewData[...]
is to Views?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
HttpContext.Current.Items
仅在请求期间持续,但对于该请求中的所有内容都是全局的。会话显然持续整个用户会话,并且在请求之间持续存在。
您应该能够仅根据这些标准来确定需要使用哪一个。我不推荐使用 HttpContext.Current.Items ,因为它往往是一种“全局变量”,而且魔术键字符串往往会涉及到,但有时您确实需要使用它。
此外,尽管 .Items 和 ViewData 之间的比较非常恰当,但 .Items 与 ViewData 的行为方式不同,因为请求中涉及的每个视图(部分或其他)都会获取自己的 ViewData 副本。
当您执行 RenderPartial 并尝试向 ViewData 添加某些内容时,行为差异很明显 - 当您返回到父视图时,该项目不在那里。
HttpContext.Current.Items
only lasts for the duration of the request, but it is global to everything in that request.Session obviously lasts for the entirety of the user's session, and persists between requests.
You should be able to figure out which one you need to use based on those criteria alone. Using
HttpContext.Current.Items
is not something I would recommend as it tends to be a kind of "global variable", and magic key strings tend to get involved, but sometimes you really do need to use it.Additionally, although your comparison between .Items and ViewData is pretty apt, .Items differs from the way that ViewData behaves, because every View involved in the request (partial or otherwise) gets their own copy of ViewData.
The behaviour difference is clear when you do a
RenderPartial
and try to add something to ViewData - when you go back up to the parent view, the item is not there.