1

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

所以一个基本的用例:

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

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

谢谢。

4

2 回答 2

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]]);
}
于 2011-07-21T03:39:10.867 回答
1

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

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

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

于 2011-07-20T23:21:38.110 回答