Server Side Session Management

From Appmethod Topics
Jump to: navigation, search

Go Up to Developing DataSnap Applications

When a client connects to a DataSnap server, a session is created. This session is represented with a TDSSession instance or subclass. The TDSAuthSession class extends TDSSession and is itself subclassed (TDSRESTSession, TDSTCPSession, TDSTunnelSession.) These instances hold a TDSCustomAuthenticationManager instance and allow for Authorization checking.

Session Lifecycle

Setting SessionTimeout

For a TDSRESTConnection how long a session is alive for can be controlled by the SessionTimeout property exposed by either the TDSHTTPServerTransport or TDSHTTPServer class. For example, the TDSHTTPService component publishes this property, as does TDSHTTPWebDispatcher. The value is set in milliseconds, and represents the amount of time which is allowed to pass of inactivity for a session before the session expires. Whenever a client issues a request to the server providing his session ID, the session is marked as active at that time, and the clock is reset for when the session will expire.

Closing a Session

To close a session, you need to know the SessionId (TDSSession.Name, actually). To close the session, simply call:


Getting the Current Thread's Session

From a server method, for example, you can obtain the current thread's session. This may provide you with useful information relating to the user issuing the current request. To do so, use the following code:

Session := TDSSessionManager.GetThreadSession;

Listening for Session Creation and Session Expiry

You can register an event with the TDSSessionManager, which will be notified when new sessions are created and old ones expire. You do so with the following code:

  procedure(Sender: TObject;
            const EventType: TDSSessionEventType;
            const Session: TDSSession)
    case EventType of
        {The provided Session was just created.}
        {The provided Session has just been closed, either intentionally or it has expired.}

If you want to later remove the event, store it in a field, and later call RemoveSessionEvent passing the event as the parameter.

Session Data

You can store data within a session. The data is stored in key/value pairs, where both the key and the value are strings.

Storing Data

To store data in a session, call PutData, passing in the key and the value to store.

Retrieving Data

To see if a value for a specific key exists, call HasData. To get a value, call GetData passing in the key as the parameter.

Removing Data

To clear a stored key/value pair from the session data, call RemoveData passing in the key as the parameter.