Facebook C# SDK - Logout

This is a continuation of the previous Facebook C# SDK tutorial on Writing your first Facebook Application. If you haven’t read it I would highly recommend to read it first.

You might had noticed that the first tutorial has a problem if you would like to sign in as a different user. Though the issue is small it must not be avoided.

When clicking “Login to Facebook” for the first time it would work as expected – it opens the browser dialog and asks for authentication. Once you authorize the app, it display a message box saying “Hi …”. Then without exiting the app, if you try to click “Login to Facebook” again, it wouldn’t ask you to sign in but rather remember the previous logged in user and say “Hi ..”. This isn’t the expected behavior. Most of the time you might want to have a button to logout or login as different user. So, in this tutorial I will show the basics on how to logout and login as different user.

Understanding the Logout mechanism:

Here is the sample code on using the new GetLogoutUrl method introduced in v5.

var oauth = new FacebookOAuthClient();

var logoutParameters = new Dictionary<string, object>
                  {
                      { "next", "http://www.facebook.com" }
                  };

var logoutUrl = oauth.GetLogoutUrl(logoutParameters);

You start by creating an instance of FacebookOAuthClient and then call GetLogoutUrl. Overwriting the “next” parameter tells the FacebookOAuthClient that once the user has been logged out, navigate to this next url – "http://www.facebook.com".

Log in as different user:

The core concept of signing in as a different user uses the help of logout mechanism by setting the appropriate next parameter. So in our case the next parameter would be login url. You can read my previous blog post on how to get the login url here.

var logoutParameters = new Dictionary<string, object>
                  {
                      { "next", loginUrl }
                  };

var logoutUrl = oauth.GetLogoutUrl(logoutParameters);

Then you would navigate the browser control to the logoutUrl instead of the login url.

webBrowser.Navigate(logoutUrl.AbsoluteUri);

Make sure you navigate to the AbsoluteUri so that it will encode the querystrings correctly.

You can download the full working sample demonstrating the problem as well as the solution of signing in as a different user.

Note: Make sure you test your facebook application to allow multiple users to sign in without exiting the application whether it is a desktop app or a windows phone application.

FacebookCSharpSdk-Logout.zip (4.57 mb)


blog comments powered by Disqus