简体   繁体   中英

Using GUID as a Session Key?

Basically I have an object that gets persisted across multiple pages, so I use Session to save and retrieve the object. I'm using a GUID for the Session key. I use a static constructor to create the GUID.

Here is an example of the object:

class Customer
{
    private static readonly string _sessionKey;

    public static string SessionKey
    {
        get { return _sessionKey; }
    }

    static Customer()
    {
        _sessionKey = Guid.NewGuid().ToString();
    }
}

Then I use it in my code like this:

Session.Add(Customer.SessionKey, new Customer());

...

Customer C = Session[Customer.SessionKey] as Customer;

I personally prefer this method instead of either a const string or a string literal for the Session key. Just wondering if there any downsides to this or what other approaches have you used?

Why do this? You should just define constants and be done with it. They aren't descriptive enough if you iterate over or use the debugger with Session .

If you have on Customer object in session - save under constant name. Otherwise consider saving collection of Customer objects under constant name.

Note: if you ever plan to use some other state provider (SQL/state service) instead of default in-memory one make sure your Customer object is serializale and makes sense between requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM