【问题标题】:Best Practices when using .NET Session for temporary storage?使用 .NET Session 进行临时存储时的最佳实践?
【发布时间】:2011-07-21 11:39:10
【问题描述】:

我对 .NET 和 ASP.NET MVC 还比较陌生,我曾有过一些情况,最好暂时存储从数据库检索到的信息,以便在后续服务器请求中使用它。客户。我已经开始使用 .NET Session 来存储这些信息,关闭时间戳,然后在我再次访问服务器时使用时间戳检索信息。

所以一个基本的用例:

  1. 用户点击“查询”按钮从系统收集信息。
  2. 在JS中,生成当前时间的时间戳,并通过请求传递给服务器
  3. 在服务器上,从数据库收集信息
  4. 在服务器上,使用来自客户端的唯一时间戳作为 Session 的键来存储响应对象。
  5. 向客户端返回响应对象
  6. 用户点击“生成报告”按钮(将查询结果格式化为 Excel 文档)
  7. 将相同的时间戳从 #2 再次传递到服务器,并用于从 #4 收集查询结果。
  8. 生成没有额外数据库命中的报告。

这是我在使用 Session 作为临时存储的任何情况下都开始使用的方案。但是在 JS 中生成时间戳并不一定是安全的,而且整个事情感觉有点……非结构化。是否有我可以使用的现有设计模式,或者更简化/安全的方法?任何帮助将不胜感激。

谢谢。

【问题讨论】:

  • JS时间戳的作用是什么?
  • JS 时间戳是一个唯一值,可以用作 Session 变量的键。我们可以很容易地生成一个随机数,但即使这样也是可重复的。

标签: asp.net session session-variables temporary


【解决方案1】:

你可以看一下TempData,它将数据存储在Session中。当你从TempData中拉出一些东西时,它将在Action执行完成后被删除。

因此,如果您在一个 Action 中放入 TempData 中的某些内容,它将在所有其他操作中存在于 TempData 中,直到再次从 TempData 请求 TempData

您也可以调用TempData.Peek("key"),它将保存在内存中,直到您调用TempData["key"]TempData.Remove("key")

【讨论】:

  • 据我了解,TempData 只对当前请求和下一个请求有效。如果我将查询的响应存储在 TempData 中(大概是在他们单击“生成报告”时进行检索)并且用户决定他们的下一个操作是 Ctrl+单击页面上的链接而不是生成报告,我就退出了当他们决定生成报告时很幸运。 ViewData 只是通过 Ctrl+click 动作才好,并且不再包含响应​​对象。有很多文章说 TempData 仅适用于重定向和重定向。
【解决方案2】:

好的,我不确定我是否理解正确,因为 JS 时间戳步骤似乎是多余的。 但这是我会做的。

public static string SessionReportKey = "Reports";
public static string ReportIDString = "ReportID";
public Dictionary<string, object> SessionReportData
{
    get
    {
        return Session[SessionReportKey] == null ? 
            new Dictionary<string, object>() : 
            (Dictionary<string, object>) Session[SessionReportKey];
    }
    set
    {
        Session[SessionReportKey] = value;
    }
}
public ActionResult PreviewReport()
{
    //retrive your data
    object reportData = GetData();

    //get identifier
    string myGUID = new GUID().ToString();

    //might only need [SessionReportData.Add(myGUID, reportData);] here
    SessionReportData = SessionReportData.Add(myGUID, reportData);

    //in your view make a hyperlink to PrintReport action with a 
    //query string of [?ReportID=<guidvalue>]
    ViewBag[ReportIDString] = myGUID;

    return View(reportData);
}


public FileContentResult PrintReport()
{
    if(SessionReportData[QueryString[ReportIDString]] == null)
    {
        //error no report in session
        return null;
    }
    return GenerateFileFromData(SessionReportData[QueryString[ReportIDString]]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 2012-07-22
    • 2010-12-30
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多