TempData won't destroy after second request

旧时模样 提交于 2019-11-26 20:43:50

问题


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.


回答1:


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");


来源:https://stackoverflow.com/questions/12815739/tempdata-wont-destroy-after-second-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!