使用.NET Session进行临时存储时的最佳实践?

时间:2011-07-20 22:55:41

标签: asp.net session session-variables temporary

我仍然是.NET和ASP.NET MVC的新手,而且我曾经有过一些时候可以暂时存储从数据库中检索到的信息,这样它就可以用于后续的服务器请求。客户。我已经开始使用.NET Session来存储这些信息,键入时间戳,然后在我再次点击服务器时使用时间戳检索信息。

所以一个基本用例:

  1. 用户点击“查询”按钮以从系统收集信息。
  2. 在JS中,生成当前时间的时间戳,并将其传递给带有请求的服务器
  3. 在服务器上,从DB收集信息
  4. 在服务器上,使用来自客户端的唯一时间戳作为会话的密钥来存储响应对象。
  5. 将响应对象返回给客户
  6. 用户点击“生成报告”按钮(将查询结果格式化为Excel文档)
  7. 将#2中的相同时间戳再次传递给服务器,并用于从#4收集查询结果。
  8. 生成没有其他数据库命中的报告。
  9. 这是我在任何使用Session作为临时存储的情况下开始使用的方案。但是在JS中生成时间戳并不一定安全,整个事情感觉有点......非结构化。我可以使用现有的设计模式,还是采用更简化/安全的方法?任何帮助将不胜感激。

    感谢。

2 个答案:

答案 0 :(得分:1)

您可以查看将TempData存储在Session中的数据。当您从TempData中取出某些内容时,它将在Action执行完后删除。

因此,如果您在一个操作中添加了TempData内容,那么它将在所有其他操作中生效TempData,直到再次从TempData请求TempData

您也可以致电TempData.Peek("key"),这会将其保留在内存中,直到您致电TempData["key"]TempData.Remove("key")

答案 1 :(得分:1)

好的,我不确定我是否理解正确,因为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]]);
}
相关问题