Mar 23

A few months back, we’ve seen how TempData is implemented and how it should be used. Today we’re going to keep looking at the future assembly and we’ll take a look at the CookieTempDataProvider class. The class implements the ITempDataProvider interface and you can use it it you intend to persist the temp data dictionary in cookies instead of relying in the traditional session temp data provider.

Internally, the class will serialize the data using the BinaryFormatter and encode it into a base 64 string which is then set as the value of a cookie which is added to the current response. Then, when the browser asks for a specific controller action and starts a subsequent request to the server, this temp data provider will search the request and see if there’s cookie with the previous persisted temp data dictionary (btw, it will search for a cookie named __ControllerTempData). If it finds one, it will rehydrate the temp data dictionary from that cookie’s value and then it will expire the cookie immediately. It will also search for an existing cookie on the response and will also invalidate it by clearing its content and expiring it (like it did to the one present on the request’s cookie collection).

The only thing you need to do is set the TempDataProvider that your controller class inherits from the Controller class. You have several options here. The important thing is that you shouldn’t set that value from the constructor of your controller because at that time your controller context is still null. A valid option could be overriding the Initialize method and set the TempDataProvider property:

protected override void Initialize(RequestContext requestContext){
  TempDataProvider = new CookieTempDataProvider( requestContext.HttpContext );

And that’s it for today! Stay tuned for more on the MVC framework.

1 comment so far

  1. Cathal
    2:55 pm - 7-17-2009

    Hi. When I setup the TempDataProvider to use the CookieTempDataProvider in this exact way, the values I write to TempData are not tracked!?

    So if I write a value to TempData, and then RedirectToAction, the new action finds that the TempData has been wiped clean.