Storing data in HttpContext.Current.Items vs ViewData
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?
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.
精彩评论