Session Handling in C# Web Services Client

The following code fragment shows the resetService method. The method creates a new VimService object and a new cookie container. The method also adds the session cookie to the cookie container.

The resetService method

/// Resetting the VimService without the security policies
/// as we need the policy only for the LoginByToken method
/// and not the other method calls. resetService also maintains the
/// authenticated session cookie post LoginByToken.
///
/// This method needs to be called only after successful
/// login
private void resetService()
{
    var _cookie = getCookie();
    _service = new VimService();
    _service.Url = _serverUrl;
    _service.CookieContainer = new CookieContainer();
    if (_cookie != null)
    {
        _service.CookieContainer.Add(_cookie);
    }
}


/// Method to save the session cookie
private Cookie getCookie()
{
    if (_service != null)
    {
        var container = _service.CookieContainer;
        if (container != null)
        {
            var _cookies = container.GetCookies(new Uri(_service.Url));
            if (_cookies.Count > 0)
            {
                return _cookies[0];
            }
        }
    }
    return null;
}