ASP.NET MVC TempData in browser cookie

后端 未结 3 696
醉梦人生
醉梦人生 2021-01-13 08:41

I am trying to use a custom ITempDataProvider provider to store TempData in a browser\'s cookie instead of session state. However, everythi

3条回答
  •  滥情空心
    2021-01-13 08:57

    Here is an example of a working solution without lots of excess code. It uses Json.NET for serializing, which is faster than BinaryFormatter + Base64Encoding and also produces a much shorter string (=less http overhead).

    public class CookieTempDataProvider : ITempDataProvider
    {
        const string cookieKey = "temp";
    
        public IDictionary LoadTempData(ControllerContext controllerContext)
        {
            var cookie = controllerContext.HttpContext.Request.Cookies[cookieKey];   
    
            if (cookie != null) {
                return JsonConvert.DeserializeObject>(cookie.Value);
            }
    
            return null;
        }
    
        // Method is called after action execution. The dictionary mirrors the contents of TempData.
        // If there are any values in the dictionary, save it in a cookie. If the dictionary is empty,
        // remove the cookie if it exists.
        public void SaveTempData(ControllerContext controllerContext, IDictionary values)
        {
            var ctx = controllerContext.HttpContext;
    
            if (values.Count > 0) {
                var cookie = new HttpCookie(cookieKey)
                {
                    HttpOnly = true,
                    Value = JsonConvert.SerializeObject(values)
                };
    
                ctx.Response.Cookies.Add(cookie);
            } else if (ctx.Request.Cookies[cookieKey] != null) {
    
                // Expire cookie to remove it from browser.
                ctx.Response.Cookies[cookieKey].Expires = DateTime.Today.AddDays(-1);
            }
        }
    }
    

提交回复
热议问题