Creating a Connect Website using FacebookSDK and ASP.NET MVC 3

The goal is to have a login link with Facebook link that lets the site personalize the content if the user wants to log in with their Facebook details. This is based on a days worth of experiments so I’m not 100% convinced I’m doing this right. Let me know in the comments if you see something wrong.

First, you need to have an application set up on Facebook. To set up your Canvas Page and Canvas URL you must first register your Facebook app and enter in your basic app information. With that complete, click the “Facebook Integration” tab on the left side of the configuration screen and make a note of the App ID and App Secret Key. Never reveal your secret key to anyone! You do not have to look at the other settings, but it is advisable to go through Facebook’s documentation and understand what they all mean.

To get started with FacebookSDK in a File|New ASP.NET MVC 3 Project, get the FacebookWebMVC package from NuGet or download package 5.0.3. You want the Newtonsoft.Json, Facebook, Facebook.Web and Facebook.Web.MVC assemblies.

Once you have referenced the right assemblies, open “/Views/Shared/_Layout.cshtml” and add the following to the bottom before the closing body tag.

    <div id="fb-root">
    </div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
        FB.init({ appId: '@Facebook.FacebookContext.Current.AppId', status: true, cookie: true, xfbml: true });
        $('#fbLogin').click(function () {
            FB.login(function (response) {
                if (response.session) {
                    window.location = '@Url.Action("AboutMe")'
                } else {
                    // user cancelled login
                }
            });
        });
        $('#fbLogout').click(function () {
            FB.logout(function (response) {window.location = '@Url.Action("Index")';});
        });
    </script>

This script block and div initializes Facebook’s JavaScript SDK and attaches the events that authenticate and authorize this site against Facebook for the current user of the browser.

Replace the contents of “/Views/Shared/_LogOnPartial.cshtml” with the following and save the image into the “/Content/” directory.

@if (Model != null && Model.Session != null)
{
    <p>Welcome <b>@Model.DisplayName</b>! <a href="#" id="fbLogout">Logout</a></p>
}
else
{
    <p>
        <img id="fbLogin" src="../../Content/login-button.png" />
    </p>
}

Login with Facebook

There’s better ways of loading data into the partial. Using a ViewModel with DisplayName and Authenticated properties would be a good start. For now, let’s carry on with the dynamic model.

Add the following to HomeController.cs

    using Facebook;
    using Facebook.Web;

// snip  

        public FacebookSession CurrentSession
        {
            get { return new Authorizer().Session; }
        }

        public ActionResult AboutMe()
        {
            dynamic model = new ExpandoObject();

            if (this.CurrentSession != null)
            {
                var app = new FacebookClient(this.CurrentSession.AccessToken);

                dynamic me = app.Get("me");
                dynamic friends = app.Get("/me/friends");

                model.Name = me.name;
                model.FriendCount = friends.data.Count;
            }
            else
            {
                model.Name = "Guest User";
                model.FriendCount = 0;
            }

            model.Session = this.CurrentSession;
            return View(model);
        }

The AboutMe is doing the heavy lifting. The Authorizer comes from the Facebook namespace and handles the session information. If it is not null we have a logged in user and can personalize data on the page. In this very simple case, a name and a friend count.

If you want to prevent a request with a null CurrentSession (i.e. a request from an unauthenticated Facebook user) add the [FacebookAuthorize] attribute to the Action method.

This works in a simple fashion but CurrentSession could do with being easily mockable and I’m a little wary of how complex the controller actions could get if I’m not careful. What would you recommend?

4 Responses to “Creating a Connect Website using FacebookSDK and ASP.NET MVC 3”

  1. Sam Says:

    I’ve managed to get an implementation of Facebook Graph API working with .NET and MVC.

    What i’ve done is created a Facebook application as usual, then in my website added a link to…

    https://www.facebook.com/dialog/oauth?client_id{YOUR_APP_ID}&redirect_uri={A_REDIRECT_URL}&Facebook/AuthResult&scope=manage_pages,offline_access,publish_stream,read_stream

    Once they’ve authorised / not authorised your website you’ll get a HTTP get request to the url you provided in the redirect_uri.

    If they allowed it you’ll get an Authorisation code, otherwise you’ll get an error_reason set… (below is my code that parses it…)

    string code = Request.QueryString["code"];

    string url = “https://graph.facebook.com/oauth/access_token?client_id={YOUR_APP_ID}&redirect_uri={REDIRECT_URL*}&client_secret={YOUR_APP_SECRET}&code={THE_CODE_YOU_JUST_GOT}”;

    This will then give you an access token which you can use for future requests.

    Enjoy!

    Sam

  2. Stephen Says:

    Nice tutorial although I’m trying to access ‘/me/albums’ but I get an empty array []. I have NO idea what’s going on here, I’m doing as my login button but it still won’t work. Do you have any ideas?

  3. Simon Gill Says:

    I’m sorry for the delay in responding to you. From the sounds of it the request you are making doesn’t have permission to view ‘/me/albums’.

    What have you managed to figure out on your own?

  4. fiverr Says:

    fiverr…

    [...]Pattern Web Solutions » Blog Archive » Creating a Connect Website using FacebookSDK and ASP.NET MVC 3[...]…

Leave a Reply