- Get FaceSharp with NuGet
- Apply Attributes on Controllers for authentication.
- Initialize Facebook JavaScript SDK Properly| Learn how to initialize the Javascript SDK AND Facesharp Server Side at the same time.
- 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:
- Add Channel.html
- Add Authorization Attribute
- Add ViewBag Data
- 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")] 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 }); };