使用 .NET Session 进行临时存储时的最佳实践?
我对 .NET 和 ASP.NET MVC 还比较陌生,并且有过几次需要暂时存储从数据库检索到的信息的情况,以便可以在客户端的后续服务器请求中使用它。我已开始使用 .NET 会话来存储此信息,关闭时间戳,然后在再次访问服务器时使用时间戳检索信息。
一个基本的用例:
- 用户单击“查询”按钮从系统收集信息。
- 在 JS 中,生成当前时间的时间戳,并通过请求将其传递给服务器。
- 在服务器上,从 DB 收集信息
- 。 在服务器上,使用客户端的唯一时间戳作为 Session 的键来存储响应对象。
- 将响应对象返回给客户端
- 用户单击“生成报告”按钮(将查询结果格式化为 Excel 文档)
- 再次将相同的时间戳从 #2 传递到服务器,并用于收集来自 #4 的查询结果。
- 生成报告,无需额外的数据库命中。
这是我在任何使用Session作为临时存储的情况下都开始使用的方案。但在 JS 中生成时间戳并不一定是安全的,而且整个事情感觉有点......非结构化。是否有我可以使用的现有设计模式,或者更精简/安全的方法?任何帮助将不胜感激。
谢谢。
I'm still relatively new to .NET and ASP.NET MVC, and I have had a few occasions where it would be nice to store information retrieved from the DB temporarily so it can be used on a subsequent server request from the client. I have begun using the .NET Session to store this information, keyed off of a timestamp, and then retrieve the information using the timestamp when I hit the server again.
So a basic use case:
- User clicks 'Query' button to gather information from the system.
- In JS, generate a timestamp of the current time, and pass this to the server with request
- On server, gather information from DB
- On server, use unique timestamp from client as a key into the Session to store the response object.
- Return response object to client
- User clicks 'Generate Report' button (will format query results into Excel doc)
- Pass same timestamp from #2 down to server again, and use to gather query results from #4.
- Generate report w/o additional DB hit.
This is the scheme that I have begun to use in any case where I use the Session as temporary storage. But generating a timestamp in JS isn't necessarily secure, and the whole things feels a little... unstructured. Is there an existing design pattern I can use for this, or a more streamlined/secure approach? Any help would be appreciated.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以查看
TempData
,它将数据存储在Session 中。当您从TempData
中提取某些内容时,它将在Action 执行完成后将其删除。因此,如果您在某个操作中将某些内容放入
TempData
中,则该内容将存在于所有其他操作中的TempData
中,直到再次从 TempData 请求TempData
为止。您还可以调用
TempData.Peek("key")
,这会将其保留在内存中,直到您调用TempData["key"]
或TempData.Remove("键”)
You may take a look at
TempData
which stores the data in Session.When you pull something out ofTempData
it will be removed after the Action is done executing.So, if you put something in
TempData
in an Action, it will live inTempData
across all other actions until its requestedTempData
from TempData again.You can also call
TempData.Peek("key")
which will keep it in memory until you callTempData["key"]
orTempData.Remove("key")
好吧,我不确定我是否正确理解你,因为 JS 时间戳步骤似乎是多余的。
但这就是我要做的。
Ok, I'm not sure I understand you correctly as the JS timestamp step seems superfluous.
But this is what I would do.