Initialize Facebook JavaScript SDK Properly

Development Guide Page 3 of 4
  1. Get FaceSharp with NuGet
  2. Apply Attributes on Controllers for authentication.
  3. Initialize Facebook JavaScript SDK Properly Learn how to initialize the Javascript SDK AND Facesharp Server Side at the same time.
  4. Make Facebook API Calls with FaceSharp

JavaScript SDK Initialization + FaceSharp Server Side Intialization

Facebook's JavaScript SDK is extremely powerful. Many projects require both server side authentication (.NET) as well as client side authentication (JavasScript). This guide will detail the process required to get both up and running.

Steps Required:
  1. Add Channel.html
  2. Add Authorization Attribute
  3. Add ViewBag Data
  4. Configure FB.Init with Javascript Object

1. Add Channel.html

Do this via your controller, example below:

Add an action :


        /// <summary>
        /// Must be long cache time:
        /// http://developers.facebook.com/docs/reference/javascript/
        /// </summary>
        [OutputCache(Duration = (60 * 60 * 24 * 365), Location = OutputCacheLocation.Any)]
        public void Channel()
        {
            Response.Cache.SetOmitVaryStar(true);
            var scheme = Request.Url == null ? "http" : Request.Url.Scheme;
            Response.Write(String.Format("<script src=\"{0}://connect.facebook.net/en_US/all.js\"></script>", scheme));
        }


Add a route :


        // Global.asax.cs - RegisterRoutes 
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute(
                "FacebookChannel",
                "channel.html",
                new { controller = "Home", action = "Channel", id = "" }
                );
        }

2. Add Authorization Attribute

Assuming that this is a Canvas Application create a method on your controller and put the authorization attribute on it to ensure visitors to the action are authenticated:


        [FacebookGraphApiFilter(CanvasRedirect = true, ForceLogin = true, ResponseType = "code token", VaryByParam = "none")]
        public ActionResult Index()
        {
            var fbApi = new FaceSharp.Api.FacebookApi();
            ViewBag.Title = "Page1";
            ViewBag.UserName = fbApi.User.GetCurrentUser().Name;
            return View();
        }


3. Add ViewBag Data

We now need to add ViewBag Data for the javascript initialization to use:
(This can be placed in a base controller's override of OnResultExecuting if desired as you'll want to have this executed on every page where you want the Facebook JavaScript API initialized.)


            ViewBag.Host = filterContext.HttpContext.Request.ServerVariables["HTTP_HOST"];
            ViewBag.Scheme = Request.Url == null ? "http" : Request.Url.Scheme;
            var facebookCore = new FacebookCore();
            ViewBag.ApplicationId = facebookCore.ApplicationId;


4. Configure FB.Init with Javascript Object

In your view, configure the Fb.init parameters cookie and channelURL (ensure oauth is true) :
(Suggestion is to place within window.fbAsyncInit)


        window.fbAsyncInit = function () {
            
            FB.init({
                appId: '@ViewBag.ApplicationId', // App ID
                channelURL: '@ViewBag.Scheme://@ViewBag.Host/channel.html', // Channel File
                status: true, // check login status
                cookie: true, // ensure client side lib is using cookies
                oauth: true, // enable OAuth 2.0
                xfbml: true  // parse XFBML
            });
        };

Last edited Jan 4, 2012 at 1:26 PM by khildreth, version 11

Comments

No comments yet.