如何在单个HTTP请求的所有调用中安全地访问单例静态值 [英] How to make singleton static value securely accessible across all calls for a single HTTP request

查看:155
本文介绍了如何在单个HTTP请求的所有调用中安全地访问单例静态值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望整个请求只能访问该请求的单例.

I want a singleton accessible to the whole request and only to calls from that request.

我有一个客户端,要求不使用内置服务器端会话. 取而代之的是,我每次都需要基于请求的cookie和查询字符串来重建UserSession对象,并使用数据库对其进行验证. 构建UserSession对象会产生一些开销,因此我只希望每个请求尽可能早地执行一次,然后在整个请求中稍后引用该对象.

I have a client with a requirement that the built-in server side session not be used. Instead I need to rebuild the UserSession object each time based on the request's cookies and query string and validate it with the database. There is some overhead in building the UserSession object, so I want to do it only once per request, as early as possible, and then reference that object later throughout the request.

当前,我正在使用OWIN中间件来调用实际构建它的Facade对象,然后将结果粘贴在用[ThreadStatic]装饰的类的静态字段中.然后,我在控制器上使用自定义的Authorize属性来检查该单例,以确保其有效.

Currently I am using OWIN middleware to call the facade object that actually builds it and then I am sticking the result in a class's static field decorated with [ThreadStatic]. I then use a custom Authorize attribute on my controllers to inspect that singleton to make sure it is valid.

第一,这在多个请求中是否安全?换句话说,使用[ThreadStatic]是否可以确保每个请求静态对象都永远不会被另一个HTTP请求访问,即使从同一浏览器会话也是如此.

First, is this secure across multiple requests? Stated differently, does the use of [ThreadStatic] ensure that each requests static object can never be accessed by another HTTP request, even from the same browser session.

第二,我是否可能在使用TPL或其他异步编程方法时遇到问题,在这些情况下,单例实例应该是可用的,因为它是同一请求,但不是因为它可能正在执行一个不同的线程.

Second, could I run into issues with using the TPL or other asyncronous programming approaches where the singleton instance should be available because it is the same request, but it is not because it might be executing on a different thread.

最后,我做错了吗?是否有比我正在做的更好或更完善的解决方案.

Lastly, am I doing wrong? Is there a better or precanned solution to this problem than what I am doing.

推荐答案

HttpContext.Current.Items是我想要的.对于这种情况,似乎存在一个简单的按请求收集.

HttpContext.Current.Items is what I was looking for. A simple per-request collection that seems to exist for this type of scenario.

这篇关于如何在单个HTTP请求的所有调用中安全地访问单例静态值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆