C# Code to get user details from FaceBook

In this blog i am going to explain about how some one can get user details from Facebook and later use data for user registration, user login and for some other purpose.

First you need to create a Facebook APP, You can check here how to create facebook app.


Once you are ready with the Facebook app, you just need to create one class and one page to get the logged in user details from Facebook.

Note: This code will work with SharePoint Websites also.

You need to download a dll – “Newtonsoft.Json.dll”

To download this dll, type “newtonsoft json dll” in google and you will get from there.


Lets start this by creating a class with name OauthFB.cs

Write below code in this class:
public class OauthFB
{
    public enum Method { GET, POST };
    public const string AUTHORIZE = “https://graph.facebook.com/oauth/authorize”;
    public const string ACCESS_TOKEN = “https://graph.facebook.com/oauth/access_token”;
    public string CALLBACK_URL = ConfigurationManager.AppSettings[“SiteUrl”];

    private string _consumerKey = “”;
    private string _consumerSecret = “”;
    private string _token = “”;

//—————————————————————————

    public string ConsumerKey
    {
        get
        {
            if (_consumerKey.Length == 0)
            {
                _consumerKey = ConfigurationManager.AppSettings[“Appid”];  
            }
            return _consumerKey;
        }
        set { _consumerKey = value; }
    }

    public string ConsumerSecret
    {
        get
        {
            if (_consumerSecret.Length == 0)
            {
                _consumerSecret = ConfigurationManager.AppSettings[“AppSecretID”];  
            }
            return _consumerSecret;
        }
        set { _consumerSecret = value; }
    }
    public string Token { get { return _token; } set { _token = value; } }

 //—————————————————————————  

    
    public string AuthorizationLinkGet()
    {
        return string.Format(“{0}?client_id={1}&redirect_uri={2}&scope={3}”, AUTHORIZE, this.ConsumerKey, CALLBACK_URL, “public_profile”);
    }

  //—————————————————————————
  
    public void AccessTokenGet(string authToken)
    {
        this.Token = authToken;
        string accessTokenUrl = string.Format(“{0}?client_id={1}&redirect_uri={2}&client_secret={3}&code={4}”,
        ACCESS_TOKEN, this.ConsumerKey, CALLBACK_URL, this.ConsumerSecret, authToken);

        string response = WebRequest(Method.GET, accessTokenUrl, String.Empty);

        if (response.Length > 0)
        {
             
            NameValueCollection qs = HttpUtility.ParseQueryString(response);

            if (qs[“access_token”] != null)
            {
                this.Token = qs[“access_token”];
            }
        }
    }

//—————————————————————————
    
    public string WebRequest(Method method, string url, string postData)
    {

        HttpWebRequest webRequest = null;
        StreamWriter requestWriter = null;
        string responseData = “”;

        webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
        webRequest.Method = method.ToString();
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.UserAgent = ConfigurationManager.AppSettings[“AmlaSiteUrl”];

        webRequest.Timeout = 30000;

        if (method == Method.POST)
        {
            webRequest.ContentType = “application/x-www-form-urlencoded”;

            requestWriter = new StreamWriter(webRequest.GetRequestStream());

            try
            {
                requestWriter.Write(postData);
            }
            catch
            {
                throw;
            }

            finally
            {
                requestWriter.Close();
                requestWriter = null;
            }
        }

        responseData = WebResponseGet(webRequest);
        webRequest = null;
        return responseData;
    }

//—————————————————————————
   
    public string WebResponseGet(HttpWebRequest webRequest)
    {
        StreamReader responseReader = null;
        string responseData = “”;

        try
        {
            responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream());
            responseData = responseReader.ReadToEnd();
        }
        catch
        {
            throw;
        }
        finally
        {
            webRequest.GetResponse().GetResponseStream().Close();
            responseReader.Close();
            responseReader = null;
        }

        return responseData;
    }
}

Now add Default.aspx page to your project.
Add below code to Default.aspx

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
    <title></title>
</head>
<body>
    <form id=”form1″ runat=”server”>
    <div>
        <asp:Button ID=”btnFBLogin” runat=”server” Text=”Login With FaceBook” 
            onclick=”btnFBLogin_Click” />
    </div>
    </form>
</body>
</html>

Add below code to Default.aspx.cs

Add these namespaces in .cs file

using Newtonsoft.Json.Linq;
using System.Web.Script.Serialization;
using System.Data.SqlClient;

Page Load


protected void Page_Load(object sender, EventArgs e)
    {        
        if (!IsPostBack)
        {
            if (Request.QueryString[“error”] != null)
            {
                if (Request.QueryString[“error”] == “access_denied”)
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), “alert”, “alert(‘User has denied access.’)”, true);
                    return;
                }
            }

            if (Request.QueryString[“code”] != null)
            {
                string code = Request.QueryString[“code”].ToString();
                OauthFB fbAC = new OauthFB(); 
                string respnse = “”;
                string token = “”;
                try
                {
                    fbAC.AccessTokenGet(code);
                    respnse = fbAC.Token;
                    token = respnse;
                }
                catch (Exception ex)
                {
                    Response.Redirect(“error.aspx?error=” + ex.Message);
                }
                string fburl = string.Format(“https://graph.facebook.com/me?access_token={0}”, token);
                OauthFB objFbCall = new OauthFB();
                string JSONReq = objFbCall.WebRequest(OauthFB.Method.GET, fburl, “”);
                JObject jObject = JObject.Parse(JSONReq);
                JToken data = jObject.Root;
                if (data.HasValues)
                {
                    string uid = (string)data.SelectToken(“id”) == null ? string.Empty : (string)data.SelectToken(“id”);
                    string firstname = (string)data.SelectToken(“first_name”) == null ? string.Empty : (string)data.SelectToken(“first_name”);
                    string lastname = (string)data.SelectToken(“last_name”) == null ? string.Empty : (string)data.SelectToken(“last_name”);
                    string gender = (string)data.SelectToken(“gender”) == null ? string.Empty : (string)data.SelectToken(“gender”);
                    string email = (string)data.SelectToken(“email”) == null ? string.Empty : (string)data.SelectToken(“email”);
                    string fullname = (string)data.SelectToken(“name”) == null ? string.Empty : (string)data.SelectToken(“name”);
                    string location = (string)data.SelectToken(“location.name”) == null ? string.Empty : (string)data.SelectToken(“location.name”);
                    string profilepic = “https://graph.facebook.com/” + uid + “/picture”;
                    if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(fullname))
                    {
                        Session[“user”] = email;
                        Session[“name”] = fullname;
                        bool result = CreateAccount(fullname, email, profilepic, location, string.Empty, gender);
                        if (result)
                        {
                            imgBtnFBLogin.Visible = false;
                            lblUserName.Text = “Hi, ” + Session[“name”].ToString();

                        }
                    }

                    else
                    {
                        Page.ClientScript.RegisterStartupScript(this.GetType(), “alert”, “alert(‘There is an erro.Please try later’)”, true);
                    }
                }
            }
        }

    }

Facebook login button code

 protected void btnFBLogin_Click(object sender, EventArgs e)
    {
        OauthFB oFB = new OauthFB();
        Response.Redirect(oFB.AuthorizationLinkGet());
    }


Create Account method once data captured from facebook

    public bool CreateAccount(string username, string email, string profile_pic, string location, string userbday, string gender)
    {

        try
        {
            //SQL Connection
            //Parameters
            //Execute non Query to insert record into database
            return true;
        }

        catch
        {
            return false;
        }

    }


Prev Blog- Facebook login using Java Script Code

2 thoughts on “C# Code to get user details from FaceBook”

Leave a Comment

RSS
YouTube
YouTube
Instagram