开发者

Static Properties with Session in ASP.NET

There are several posts about this online but none seem to provide a definitive answer. My question is this. If I have static properties declared that solely get/set Session values is that thread safe or will it potentially cause problems? In my app I have added static properties to my Global.asax to serve as a sort of central entry point for accessing certain values, for example I store the current client like this:

public static string CurrentClient {
    get {
      return HttpContext.Current.Session[Constants.SESSION_CURRENT_CLIENT] as string;
    }
    set {
      HttpContext.Current.Session[Constants.SESSION_CURRENT_CLIENT] = value;
    }
}

Note how I am not setting any static variables in my get/set, I am merely referencing the current session.

The application is setup so that it is installed as a single webapp in IIS but it will service multiple different 'instances'. Basically depending on what subdomain you come in on, it will then set all these Session variables as required. So for example:

client1.mydomain.com will set:

Global.CurrentClient = "client1";

client2.mydomain.com will set:

Global.CurrentClient = "client2";

This seems like it should work fine and be thread safe and the two subdomains will not trip over one another because they should each have unique sessions but that's exactly what seems to be happening. I get requests to client1.mydomain.com using CurrentClient="client2" for some reason.

What's going on here gan开发者_如何转开发g?


You seem to have a bad case of static-phobia. You shouldn't listen to people who spread FUD just because they don't understand what they're doing.

Static properties are essentially static methods. They do not store any state by themselves. Auto-properties are of course an exception, but you don't seem to be using them.

As long as you access any shared state in your static properties in a thread-safe manner, you won't have any problems.

What comes to your sessions getting "mixed up", are you sure the session cookie is being set at the correct level? If you set it at the mydomain.com level, it's going to be shared across all the subdomains. Also, are you sure it's even necessary to store this stuff in the session? Wouldn't it be the easiest to just compare the current domain with your list of clients on every request?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜