Click here to Skip to main content
12,078,489 members (48,711 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

72K views
34 bookmarked
Posted

Get user Facebook details in ASP.NET and C#

, 23 Apr 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Connect to Facebook and get user Facebook details.

Introduction

I am going to teach you how to add Facebook login functionality in your web application using C#. First, you need to create a Facebook account (if you haven’t already) and then activate your developer account by visiting this link: https://developers.facebook.com.

Once you have created it, now you can create an app by clicking on the Apps link, circled in the below image.

Apps.png

Now follow the steps and you’ll see the App ID and the secret key.

Step 1: Enter your app name here.

step1.png

Step 2:

step2.png

Step 3: Final step. Here you can see your app Id and app secret key. You need to mentione your domain name and site URL. This can be either an offline or online URL.

finalstep.png

Once your app is setup, now we can move to the coding part.

Page 1: In the first ASPX (facebook_login.aspx) page, write the below code.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class facebook_login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string host = Request.ServerVariables["HTTP_HOST"];
        string facebookClientId = 
          System.Configuration.ConfigurationManager.AppSettings["FacebookClientId"];
        string RedirectURL = "";
        if (Request.QueryString["redirectURL"] != null)
        {
            RedirectURL = Request.QueryString["redirectURL"].ToString();
            Session["RedirectURL"] = RedirectURL;
        }
        Response.Redirect(@"https://graph.facebook.com/oauth/authorize?client_id=" + 
          facebookClientId + "&redirect_uri=http://" + host + 
          @"/FBcallback.aspx&scope=publish_stream,offline_access,publish_actions");
    }
}

Here we are redirecting users to the Facebook page for the user to login to his/her Facebook account.

Parameters passed in the above API:

  • client_id: this is a our AppID that we have created above, i.e., 414331798577752.
  • redirect_uri: this will be our page link. Facebook will redirect the user to this page after login.
  • scope: the permissions we want from the user to accept; we need this to post data on the user’s wall.

Page 2 (Fbcallback.aspx): In this page we will get code from the first page and get the access token using that code value.

public partial class FBcallback : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["code"] != null)
        {
            
            string code = Request.QueryString["code"].ToString();

            oAuthFacebooks fbAC = new oAuthFacebooks(); //Standard FB class file available on net in c#
            string respnse = "";
            try
            {              
                fbAC.AccessTokenGet(code);
                respnse = fbAC.Token;
            }
            catch (Exception ex)
            {
                Response.Redirect("http://localhost:8020/aspx/SiteLogin.aspx?error=" + ex.Message);
            }

            if (Session["RedirectURL"] != null && Session["RedirectURL"].ToString() != "")
            {
                Response.Redirect(Session["RedirectURL"].ToString() + "?token=" + respnse + "&source=FB");
            }
            else
            {
                Response.Redirect("http://localhost:8020/aspx/SiteLogin.aspx?token=" + respnse);
            }
      
    }
    else
    {
        Response.Redirect("http://localhost:8020/aspx/SiteLogin.aspxerror=code not found" + 
                          Request.QueryString["error_reason"].ToString());
    }
}

Page 3: SiteLogin.aspx - now we get the access token and using it we can get the user’s Facebook details.

string token = Request.QueryString["token"];
string HitURL = string.Format("https://graph.facebook.com/me?access_token={0}", token);
oAuthFacebooks objFbCall = new oAuthFacebooks();
string JSONInfo = objFbCall.WebRequest(oAuthFacebooks.Method.GET, HitURL, "");

JObject Job = JObject.Parse(JSONInfo);
JToken Jdata = Job.Root;

if (Jdata.HasValues)
{
    string UID = (string)Jdata.SelectToken("id");
    string firstname = (string)Jdata.SelectToken("first_name");
    string lastname = (string)Jdata.SelectToken("last_name");
    Response.Write(UID + “-” + firstname + “-” + lastname);
}

You need to add the namespace Newtonsoft.Json.Linq for JSON data parsing. Here we are making a web request to the Facebook API (https://graph.facebook.com/me?) and passing an active access token to get the user's Facebook details. It will get returned by Facebook in JSON format. We have used the JSON parser to do the job.

Thanks folks, I hope this will be useful for you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

AbdulMuheet
Software Developer (Senior) sportz Interactive
India India
Abdul Muheet is a senior web developer working at Sportz Interactive, he enjoy working with microsoft technologies. have worked with C#, Asp.Net, Ajax, XML, Javascript and so on.

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
khurram ali lashari14-Dec-14 12:03
professionalkhurram ali lashari14-Dec-14 12:03 
QuestionIssue while redirecting to fbcallback page Pin
Member 1032546224-Dec-13 2:56
memberMember 1032546224-Dec-13 2:56 
Questiongot an error Pin
ayyappadasnk2-May-13 3:30
memberayyappadasnk2-May-13 3:30 
AnswerRe: got an error Pin
AbdulMuheet2-May-13 4:13
memberAbdulMuheet2-May-13 4:13 
Questiondownload project Pin
Member 995471814-Apr-13 1:52
memberMember 995471814-Apr-13 1:52 
GeneralMy vote of 1 Pin
dipak biswas18-Feb-13 3:24
memberdipak biswas18-Feb-13 3:24 
Questiongetting facebook pages Pin
NaniCh16-Aug-12 20:34
memberNaniCh16-Aug-12 20:34 
GeneralAccess Token Doesn't get Pin
NaniCh13-Jul-12 1:53
memberNaniCh13-Jul-12 1:53 
Questiontoken doesn't get Pin
NaniCh11-Jul-12 4:15
memberNaniCh11-Jul-12 4:15 
QuestionDoesn't getting values Pin
NaniCh29-Jun-12 8:42
memberNaniCh29-Jun-12 8:42 
AnswerRe: Doesn't getting values Pin
AbdulMuheet30-Jun-12 21:47
memberAbdulMuheet30-Jun-12 21:47 
QuestionDoesn't getting values Pin
NaniCh28-Jun-12 8:41
memberNaniCh28-Jun-12 8:41 
AnswerRe: Doesn't getting values Pin
AbdulMuheet28-Jun-12 21:12
memberAbdulMuheet28-Jun-12 21:12 
GeneralRe: Doesn't getting values Pin
NaniCh28-Jun-12 22:32
memberNaniCh28-Jun-12 22:32 
QuestionGetting 'ASP.facebook_login_aspx.GetTypeHashCode()': no suitable method found to override error Pin
NaniCh21-Jun-12 2:54
memberNaniCh21-Jun-12 2:54 
QuestionWhere do you find the oAuthFacebooks dll? Pin
Member 767651828-May-12 10:20
memberMember 767651828-May-12 10:20 
AnswerRe: Where do you find the oAuthFacebooks dll? Pin
AbdulMuheet28-May-12 20:48
memberAbdulMuheet28-May-12 20:48 
BugRe: Where do you find the oAuthFacebooks dll? Pin
Omprakash Kukana27-Sep-13 21:59
professionalOmprakash Kukana27-Sep-13 21:59 
GeneralRe: Where do you find the oAuthFacebooks dll? Pin
Mohan Wakle9-Oct-13 2:32
memberMohan Wakle9-Oct-13 2:32 
QuestionError Pin
fdffggfgfgfgfgfgf27-May-12 3:49
memberfdffggfgfgfgfgfgf27-May-12 3:49 
AnswerRe: Error Pin
AbdulMuheet27-May-12 20:42
memberAbdulMuheet27-May-12 20:42 
GeneralRe: Error Pin
NaniCh11-Jul-12 20:07
memberNaniCh11-Jul-12 20:07 
GeneralRe: Error Pin
ayyappadasnk2-May-13 20:29
memberayyappadasnk2-May-13 20:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.160212.1 | Last Updated 23 Apr 2012
Article Copyright 2012 by AbdulMuheet
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid