Skip to content

Instantly share code, notes, and snippets.

@wshaddix
Created May 22, 2014 00:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wshaddix/869dbf0b3bc3b3deeead to your computer and use it in GitHub Desktop.
Save wshaddix/869dbf0b3bc3b3deeead to your computer and use it in GitHub Desktop.
Cookie based TempData provider for Asp.Net MVC applications that don't want to use Session to store TempData content
public class CookieTempDataProvider : ITempDataProvider
{
private const string CookieName = "TempData";
private readonly IFormatter _formatter;
public CookieTempDataProvider()
{
_formatter = new BinaryFormatter();
}
public IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
{
var cookie = controllerContext.HttpContext.Request.Cookies[CookieName];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
var bytes = Convert.FromBase64String(cookie.Value);
using (var stream = new MemoryStream(bytes))
{
return _formatter.Deserialize(stream) as IDictionary<string, object>;
}
}
return new Dictionary<string, object>();
}
public void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
{
var cookie = new HttpCookie(CookieName) { HttpOnly = true };
if (values.Count == 0)
{
cookie.Expires = DateTime.Now.AddDays(-1);
cookie.Value = string.Empty;
controllerContext.HttpContext.Response.Cookies.Set(cookie);
return;
}
using (var stream = new MemoryStream())
{
_formatter.Serialize(stream, values);
var bytes = stream.ToArray();
cookie.Value = Convert.ToBase64String(bytes);
}
controllerContext.HttpContext.Response.Cookies.Add(cookie);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment