将 TempData 与 Post 重定向获取模式结合使用

Using TempData with Post Redirect Get pattern

有很多人提倡在 .NET Core 2 中将 TempData 与 PRG 模式一起使用。2.x。

据我了解,这行代码存储数据:

 TempData["foo"] = JsonConvert.SerializeObject(model);

下面重新构造模型,然后将其从 TempData 构造中删除:

string s = (string)TempData["Model"];
var model = JsonConvert.DeserializeObject<ModelType>(s);

鉴于 TempData 的这种瞬态特性,想象一下以下 PRG 构造。用户 POST 到 UserInfo 操作,该操作将模型打包到 TempData 并重定向到 UserInfo GET。 GET UserInfo 重构模型并显示视图。

[HttpPost]
public IActionResult UserInfo(DataCollectionModel model) {
    TempData["Model"] = JsonConvert.SerializeObject(model);
    return RedirectToAction("UserInfo");
}

[HttpGet]
public IActionResult UserInfo() {
    string s = (string)TempData["Model"];
    DataCollectionModel model = JsonConvert.DeserializeObject<DataCollectionModel>(s);
    return View(model);
}

用户现在位于 /Controller/UserInfo 页面。如果用户按 F5 刷新页面,TempData["Model"] 将不再存在并且 UserInfo 上的 GET 将失败。修复方法可能是在读取模型后将模型存储在 TempData 中,但这不会导致内存泄漏吗?

我是不是漏掉了什么?

TempData 可用于存储瞬态数据。它对于重定向很有用,当需要多个数据时 request.When 读取 TempDataDictionary 中的对象,它将在该请求结束时标记为删除。

这意味着如果你把一些东西放在 TempData 上,比如

TempData["value"] = "someValueForNextRequest";

并且在您访问它的另一个请求中,该值将在那里,但一旦您读取它,该值将被标记为删除:

//second request, read value and is marked for deletion
object value = TempData["value"];

//third request, value is not there as it was deleted at the end of the second request
TempData["value"] == null

Peek 和 Keep 方法允许您读取值而无需将其标记为删除。假设我们回到将值保存到 TempData 的第一个请求。

使用 Peek,您无需通过一次调用将其标记为删除即可获取值,请参阅 msdn:

//second request, PEEK value so it is not deleted at the end of the request
object value = TempData.Peek("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

使用 Keep 可以指定要保留的标记为删除的密钥。检索对象和稍后将其保存免于删除是 2 个不同的调用。参见 msdn

//second request, get value marking it from deletion
object value = TempData["value"];
//later on decide to keep it
TempData.Keep("value");

//third request, read value and mark it for deletion
object value = TempData["value"];

当您总是想为另一个请求保留值时,可以使用 Peek。当保留值取决于附加逻辑时使用 Keep。

在您的获取操作中进行以下更改

public IActionResult UserInfo()
    {
        //The First method ,
        string s = (string)TempData.Peek("Model");

        //The Second method
        string s = (string)TempData["Model"]; 
        TempData.Keep("Model");

        if(s==null)
        {
            return View();
        }
        else
        {
            User model = JsonConvert.DeserializeObject<User>(s);
            return View(model);
        }
    }