TempData 不会在第二次请求后销毁 [英] TempData won't destroy after second request

查看:29
本文介绍了TempData 不会在第二次请求后销毁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 actionfilter 中的第一个请求时将一个值放入 TempData.

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

并且该值仍然存在.这个值不应该在第二次请求后销毁吗?所有请求都是 AJAX 请求.

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

推荐答案

这个值不应该在第二次请求后销毁吗?

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

仅当您阅读它时:

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

如果你不从 TempData 读取值,它不会被驱逐.

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

TempData.Items 获取器的定义如下:

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

注意仅当您调用 getter 并且仅当在集合中找到该值时,该值将如何被驱逐.在您展示的代码中,您所做的只是检查 TempData 是否包含给定的键,但您还没有读取该键的值.

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.

如果需要,您可以手动逐出 TempData 值:

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

这篇关于TempData 不会在第二次请求后销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆