I wrote the following method to automatically request new session when session expiration is detected:
> string cookieName = null;
string sessionId = null; DateTime sessionExpiry = DateTime.Now; private void HandleSessionExpired(Replication replication) { bool isUnauthorized = false; var exception = replication.LastError as HttpResponseException; if (exception != null) { isUnauthorized = exception.StatusCode == HttpStatusCode.Unauthorized; } else { var couchbaseLiteException = replication.LastError as CouchbaseLiteException; isUnauthorized = couchbaseLiteException.Message.Contains("Unauthorized"); }
if (isUnauthorized) { if (sessionExpiry <= DateTime.Now) CreateCouchbaseSession(out this.cookieName, out this.sessionId, out sessionExpiry);
replication.Stop(); replication.DeleteCookie(cookieName); replication.SetCookie(cookieName, sessionId, "/", sessionExpiry, false, true); //replication.LastError = null; replication.Start(); } }
As you can see, it create a new token, stop the current pulling/pushing, delete existing SyncGatewaySession cookie resetting to new session cookie and start the pulling/pushing again. (I also tried to use Restart() method instead)
But the above code doesn’t solve the problem even I set the replication to new session, the property LastError still remain the same value. I tried to set LastError to null, but its throw:
NullReferenceException: Object reference not set to an instance of an object
What is the proper way to set a new session token?