Using cookies to store session in ASP MVC

Christopher Stott picture Christopher Stott · Oct 30, 2009 · Viewed 10.8k times · Source

Storing the entire session in a cookie has been standard in Rails for the last few years - is there an easy way to achieve something similar with ASP MVC?

By default, anything in Session / TempData is stored in memory on the server. In web.config this can be changed to an SQL Store / server-side cache. I'd like to be able to have these objects persisted in a cookie.

It looks like I could implement a custom Session-State Store Provider. Is there a simpler approach?

Answer

axel_c picture axel_c · Nov 10, 2009

I think it would be much more efficient to just store the session ID (a hash or whatever) in the cookie, and then use that ID to get the session data from memory / database / whatever storage you prefer. Keeping the full session state in a cookie increases bandwidth innecessarily.

Also, keep security in mind: if the cookie contains authentication information or other sensitive data and you're not careful, it can easily be hacked by the user to gain privileges or otherwise mess with your application (encrypting the data sucks too, because then you have to base-64 encode the encrypted data, which further wastes bandwidth and processing time). You should never trust input from the user.