Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET MVC CookieTempDataProvider
public class CookieTempDataProvider : ITempDataProvider
{
// Change cookie name to whatever you want it to be
const string TempDataCookieKey = "__TempData";
HttpContextBase httpContext;
#region Constructors
public CookieTempDataProvider(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
this.httpContext = httpContext;
}
#endregion
public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
{
var cookie = httpContext.Request.Cookies[TempDataCookieKey];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
var deserializedTempData = DeserializeTempData(cookie.Value);
ResetCookie();
return deserializedTempData;
}
return new Dictionary<string, object>();
}
public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
{
string cookieValue = string.Empty;
if (values != null && values.Count > 0)
{
var cookie = new HttpCookie(TempDataCookieKey);
cookie.Value = SerializeToBase64EncodedString(values);
cookie.HttpOnly = true;
httpContext.Response.Cookies.Add(cookie);
}
}
#region Helpers
void ResetCookie()
{
var cookie = new HttpCookie(TempDataCookieKey);
cookie.Expires = DateTime.MinValue;
cookie.Value = string.Empty;
cookie.HttpOnly = true;
httpContext.Response.Cookies.Add(cookie);
}
IDictionary<string, object> DeserializeTempData(string base64EncodedSerializedTempData)
{
try
{
byte[] bytes = Convert.FromBase64String(base64EncodedSerializedTempData);
var memStream = new MemoryStream(bytes);
var binFormatter = new BinaryFormatter();
return binFormatter.Deserialize(memStream, null) as IDictionary<string, object>;
}
catch (System.FormatException)
{
// ignore invalid format exceptions
return new Dictionary<string, object>();
}
catch (Exception)
{
throw;
}
}
string SerializeToBase64EncodedString(IDictionary<string, object> values)
{
using (var memStream = new MemoryStream())
{
var binFormatter = new BinaryFormatter();
binFormatter.Serialize(memStream, values);
memStream.Position = 0;
byte[] bytes = memStream.ToArray();
return Convert.ToBase64String(bytes);
}
}
#endregion
}
public class MyBaseController: Controller
{
/// <summary>
/// Overrides the creation of the TempDataProvider
/// to use a Cookie based TempDataProvider instead of Session
/// </summary>
protected override ITempDataProvider CreateTempDataProvider()
{
return new CookieTempDataProvider(HttpContext);
}
}
@karlosRivera

This comment has been minimized.

Show comment
Hide comment
@karlosRivera

karlosRivera Oct 20, 2016

How to use CookieTempDataProvider to store and retrieve data from action method?

karlosRivera commented Oct 20, 2016

How to use CookieTempDataProvider to store and retrieve data from action method?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment