Wednesday, April 2, 2014

How to add Facebook login function into ASP.NET MVC project?

Step 1: create a Facebook app, and get appid
Step 2: Add following code into login view file


Step 3: Create an action in AccountController
        [HttpGet]
        public ActionResult FacebookLogin(string token)
        {
            WebClient client = new WebClient();
            string JsonResult = client.DownloadString(string.Concat(
                   "https://graph.facebook.com/me?access_token=", token));

            var serializer = new JavaScriptSerializer();
            dynamic value = serializer.DeserializeObject(JsonResult);
            
            var model = new RegisterModel()
            {
                Email = value["email"],
                FirstName = value["first_name"],
                LastName = value["last_name"]
            };

            FormsAuthentication.SetAuthCookie(model.Email, true /* createPersistentCookie */);
            return RedirectToAction("Index", "Home");
        }

No comments:

Post a Comment