【发布时间】:2015-02-05 18:18:12
【问题描述】:
我正在尝试使用 TempData 将数据从一个请求发送到另一个请求。
但是,由于 TempData 使用服务器会话,并且此应用程序是网络农场的,因此我将不得不使用 cookie 或数据库持久性,因为会话不会从一台服务器传输到另一台服务器。
有许多实现可以使用 cookie 代替默认会话:
public class CookieTempDataProvider : ITempDataProvider
{
const string CookieName = "TempData";
public void SaveTempData(
ControllerContext controllerContext,
IDictionary<string, object> values)
{
// convert the temp data dictionary into json
string value = Serialize(values);
// compress the json (it really helps)
var bytes = Compress(value);
// sign and encrypt the data via the asp.net machine key
value = Protect(bytes);
// issue the cookie
IssueCookie(controllerContext, value);
}
public IDictionary<string, object> LoadTempData(
ControllerContext controllerContext)
{
// get the cookie
var value = GetCookieValue(controllerContext);
// verify and decrypt the value via the asp.net machine key
var bytes = Unprotect(value);
// decompress to json
value = Decompress(bytes);
// convert the json back to a dictionary
return Deserialize(value);
}
...
参考。 http://brockallen.com/2012/06/11/cookie-based-tempdata-provider/
但是,这些方法似乎都不会在请求结束后删除 cookie。
在请求完成后使用 TempData 使数据过期不就是重点吗(除非您使用 TempData.Keep("myKey");)?
为什么不直接使用 cookie 而不是实现 ITempDataProvider?有什么区别/好处?
进一步阅读:
这是一个更简单的基于 cookie 的实现:
这是微软对 SessionState 提供者的实现:
为澄清而编辑:在以下代码中,Microsoft 在加载会话后将其删除,以使其无法再次加载:
// If we got it from Session, remove it so that no other request gets it
session.Remove(TempDataSessionStateKey);
【问题讨论】:
-
在您的实现中删除 cookie 有什么问题?
-
嗯,我有点好奇为什么我发现的其他实现都没有删除 cookie。我希望 cookie 被删除,就像微软删除会话一样;然而,这不是我在上面提到的 Brock Allen 的代码中发现的。
标签: c# asp.net-mvc cookies tempdata