How to make singleton static value securely access

2019-08-19 07:01发布

问题:

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

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.

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.

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.

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.

回答1:

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