Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4059768
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T15:15:04+00:00 2026-05-20T15:15:04+00:00

I am trying to use a custom ITempDataProvider provider to store TempData in a

  • 0

I am trying to use a custom ITempDataProvider provider to store TempData in a browser’s cookie instead of session state. However, everything works fine except that I am unable to remove the cookie from the Response stream after reading it.

Any ideas?
Thanks!

public class CookieTempDataProvider : ITempDataProvider
    {
        internal const string TempDataCookieKey = "__ControllerTempData";
        HttpContextBase _httpContext;

        public CookieTempDataProvider(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            _httpContext = httpContext;
        }

        public HttpContextBase HttpContext
        {
            get
            {
                return _httpContext;
            }
        }

        protected virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
        {
            HttpCookie cookie = _httpContext.Request.Cookies[TempDataCookieKey];
            if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
            {
                IDictionary<string, object> deserializedTempData = DeserializeTempData(cookie.Value);

                // Remove cookie                
                cookie.Expires = DateTime.MinValue;
                cookie.Value = string.Empty;
                _httpContext.Request.Cookies.Remove(TempDataCookieKey);

                if (_httpContext.Response != null && _httpContext.Response.Cookies != null)
                {
                    HttpCookie responseCookie = _httpContext.Response.Cookies[TempDataCookieKey];
                    if (responseCookie != null)
                    {
                        // Remove cookie
                        cookie.Expires = DateTime.MinValue;
                        cookie.Value = string.Empty;
                        _httpContext.Response.Cookies.Remove(TempDataCookieKey);

                    }
                }

                return deserializedTempData;
            }

            return new Dictionary<string, object>();
        }

        protected virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
        {

            string cookieValue = SerializeToBase64EncodedString(values);  
            var cookie = new HttpCookie(TempDataCookieKey);
            cookie.HttpOnly = true;
            cookie.Value = cookieValue;

            _httpContext.Response.Cookies.Add(cookie);
        }

        public static IDictionary<string, object> DeserializeTempData(string base64EncodedSerializedTempData)
        {
            byte[] bytes = Convert.FromBase64String(base64EncodedSerializedTempData);
            var memStream = new MemoryStream(bytes);
            var binFormatter = new BinaryFormatter();
            return binFormatter.Deserialize(memStream, null) as IDictionary<string, object> /*TempDataDictionary : This returns NULL*/;
        }

        public static string SerializeToBase64EncodedString(IDictionary<string, object> values)
        {
            MemoryStream memStream = new MemoryStream();
            memStream.Seek(0, SeekOrigin.Begin);
            var binFormatter = new BinaryFormatter();
            binFormatter.Serialize(memStream, values);
            memStream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = memStream.ToArray();
            return Convert.ToBase64String(bytes);
        }

        IDictionary<string, object> ITempDataProvider.LoadTempData(ControllerContext controllerContext)
        {
            return LoadTempData(controllerContext);
        }

        void ITempDataProvider.SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
        {
            SaveTempData(controllerContext, values);
        }
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T15:15:04+00:00Added an answer on May 20, 2026 at 3:15 pm

    Hi I too had the same issue and it was an issue with the implementation of CookieTempDataProvider.

    So I modified the code a bit and now it works perfectly.

    When it reads the data from the cookie, it removes it from both the request and response. But add another cookie with an empty value in the SaveData function which is called when the request processing is completed.

    Points to note : If you want to remove a cookie, you have to set the timeout value and send it back to the client and then the browser will remove it. We cannot do it otherwise from the code a the cookie is handled by the browser

    And I found out that setting the expiration to DateTime.MinValue does not expire the cookie in chrome (don’t know about the other browsers) so I set it to 2001-01-01 🙂

    Here is the working code

    public class CookieTempDataProvider : ITempDataProvider
    {
        internal const string TempDataCookieKey = "__ControllerTempData";
        HttpContextBase _httpContext;
    
        public CookieTempDataProvider(HttpContextBase httpContext)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            _httpContext = httpContext;
        }
    
        public HttpContextBase HttpContext
        {
            get
            {
                return _httpContext;
            }
        }
    
        protected virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext)
        {
            if (_httpContext.Request.Cookies.AllKeys.Contains(TempDataCookieKey)) //we need this because
            //Cookies[TempDataCookieKey] will create the cookie if it does not exist
            {
                HttpCookie cookie = _httpContext.Request.Cookies[TempDataCookieKey];
                if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
                {
                    IDictionary<string, object> deserializedTempData = DeserializeTempData(cookie.Value);
    
                    // Remove cookie                
                    cookie.Expires = new DateTime(2000, 1, 1);
                    cookie.Value = string.Empty;
                    _httpContext.Request.Cookies.Remove(TempDataCookieKey);
    
                    if (_httpContext.Response != null && _httpContext.Response.Cookies != null)
                    {
                        HttpCookie responseCookie = _httpContext.Response.Cookies[TempDataCookieKey];
                        if (responseCookie != null)
                        {
                            // Remove cookie
                            cookie.Expires = new DateTime(2000, 1, 1);
                            cookie.Value = string.Empty;
                            _httpContext.Response.Cookies.Remove(TempDataCookieKey);
    
                        }
                    }
    
                    return deserializedTempData;
                }
            }
            return new Dictionary<string, object>();
        }
    
        protected virtual void SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
        {
            if (values != null && values.Count > 0)
            {
                //there are values to set, so add the cookie. But no need to expire it as we need the browser to send the 
                //cookie back with the next request
                string cookieValue = SerializeToBase64EncodedString(values);
                var cookie = new HttpCookie(TempDataCookieKey);
                cookie.HttpOnly = true;
                cookie.Value = cookieValue;
    
                _httpContext.Response.Cookies.Add(cookie);
            }
            else
            {
                //Still we need to add the cookie with the expiration set, to make the client browser remove the cookie from the request.
                //Otherwise the browser will continue to send the cookie with the response
    
                //Also we need to do this only if the requet had a tempdata cookie
    
                if (_httpContext.Request.Cookies.AllKeys.Contains(TempDataCookieKey))
                {
                    {
                        HttpCookie cookie = _httpContext.Request.Cookies[TempDataCookieKey];
    
                        // Remove the request cookie                
                        cookie.Expires = new DateTime(2000, 1, 1);
                        cookie.Value = string.Empty;
                        _httpContext.Request.Cookies.Remove(TempDataCookieKey);
    
                        var rescookie = new HttpCookie(TempDataCookieKey);
                        rescookie.HttpOnly = true;
                        rescookie.Value = "";
                        rescookie.Expires = new DateTime(2000, 1, 1); //so that the browser will remove the cookie when it receives the request
                        _httpContext.Response.Cookies.Add(rescookie);
                    }
                }
            }
        }
    
        public static IDictionary<string, object> DeserializeTempData(string base64EncodedSerializedTempData)
        {
            byte[] bytes = Convert.FromBase64String(base64EncodedSerializedTempData);
            var memStream = new MemoryStream(bytes);
            var binFormatter = new BinaryFormatter();
            return binFormatter.Deserialize(memStream, null) as IDictionary<string, object> /*TempDataDictionary : This returns NULL*/;
        }
    
        public static string SerializeToBase64EncodedString(IDictionary<string, object> values)
        {
            MemoryStream memStream = new MemoryStream();
            memStream.Seek(0, SeekOrigin.Begin);
            var binFormatter = new BinaryFormatter();
            binFormatter.Serialize(memStream, values);
            memStream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = memStream.ToArray();
            return Convert.ToBase64String(bytes);
        }
    
        IDictionary<string, object> ITempDataProvider.LoadTempData(ControllerContext controllerContext)
        {
            return LoadTempData(controllerContext);
        }
    
        void ITempDataProvider.SaveTempData(ControllerContext controllerContext, IDictionary<string, object> values)
        {
            SaveTempData(controllerContext, values);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to use a custom validator with jQuery Validation plugin. However, I'm unsure
I'm trying to use custom container widgets in gtk.Builder definition files. As far as
I'm trying to use a custom configuration section, something I've done numerous times before
I'm trying to use multiple attributes in my custom tag, e.g.: <mytaglib:mytag firstname=Thadeus lastname=Jones
I'm building a custom web part for SharePoint and I'm trying to use the
I'm trying to serialize a custom class that needs to use multiple elements of
I am trying to use custom error pages using redirects in IIS7. This is
HI, I am trying to use custom decorators with Zend_Form. I created custom decorator
When trying to use a custom JSP tag library, I have a variable defined
I'm trying to use a custom maven wagon extension to deploy a jar to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.