TempData won't destroy after second request

user49126 picture user49126 · Oct 10, 2012 · Viewed 15.8k times · Source

I'm putting a value into TempData on first request in an actionfilter.

filterContext.Controller.TempData["value"] = true;

after that a second request comes in and I check for the value

filterContext.Controller.TempData.ContainsKey("value")

the value is there. Then a third request comes in and I check for the value again

filterContext.Controller.TempData.ContainsKey("value")

and the value is still present. Shouldn't be this value destroyed after the second request ? All request are AJAX requests.

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 10, 2012

Shouldn't be this value destroyed after the second request ?

Only if you read it:

var value = filterContext.Controller.TempData["value"];

If you don't read the value from the TempData it won't be evicted.

Here's how the TempData.Items getter is defined:

public object get_Item(string key)
{
    object obj2;
    if (this.TryGetValue(key, out obj2))
    {
        this._initialKeys.Remove(key);
        return obj2;
    }
    return null;
}

Notice how the value will be evicted only if you call the getter and only if the value was found in the collection. In the code you have shown all you do is check whether the TempData contains a given key but you haven't read the value of this key.

You could manually evict the TempData value if you want:

filterContext.Controller.TempData.Remove("value");

And there's also a method which allows you to read the value without removing it:

var value = filterContext.Controller.TempData.Peek("value");