Click here to Skip to main content
15,881,789 members
Articles / Web Development / ASP.NET
Tip/Trick

Posting on a Facebook page in ASP.NET

Rate me:
Please Sign up or sign in to vote.
3.79/5 (9 votes)
2 Aug 2012CPOL1 min read 81.7K   12   27
How to post on a Facebook page from ASP.NET.

Introduction

This article explains how to post on a Facebook page from ASP.NET.

Using the code

First register your application and get the client ID. Then after the user authenticates your app, you will get an Access Token.

Authentication process

First, place two buttons for authorization on a webform. In the authorization button click event, write the following code. We set Offline access, Publish stream permission, and manage Pages Permission of users to post on page.

C#
protected void Authorization_Click(object sender, EventArgs e)
{
    //     Your Website Url which needs to Redirected
    string callbackUrl = "xxxxxxx";

    //Client Id Which u Got when you Register You Application
    string   FacebookClientId="xxxx";
    Response.Redirect(string.Format("https://graph.facebook.com/oauth/" + 
      "authorize?client_id={0}&redirect_uri={1}&scope=offline_access," + 
      "publish_stream,read_stream,publish_actions,manage_pages",
      FacebookClientId, callbackUrl));
}

After user authorizes, you will receive an Oauth code. Use the below URL to get the access token for that user.

https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=The code U got from face book after Redirecting

This will return the User Access token, save it for further use. After this we need to get the Pages information of the user.

Use the below method to get page tokens and IDs:

C#
public void getpageTokens()
{
    // User Access Token  we got After authorization
    string UserAccesstoken="xxxxxx";
    string url = string.format("https://graph.facebook.com/" + 
                 "me/accounts?access_token={0}",UserAccesstoken);

    webRequest.ContentType = "application/x-www-form-urlencoded";
    webRequest.Method = "Get";
            
    var webResponse = webRequest.GetResponse();
    StreamReader sr = null;
                    
    sr = new StreamReader(webResponse.GetResponseStream());
    var vdata = new Dictionary<string, string>();
    string returnvalue = sr.ReadToEnd();

    //using Jobject to parse result
    JObject mydata = JObject.Parse(returnvalue);
    JArray data = (JArray)mydata["data"];
              
    PosttofacePage(data);
}

I used the Json.net DLL to parse information from Facebook. The DLL can be found here.

Now it is time to post data to pages:

C#
public void PosttofacePage(JArray obj)
{
    for (int i = 0; i < obj.Count; i++)
    {
        string name = (string)obj[i]["name"];
        string Accesstoken = (string)obj[i]["access_token"];
        string category = (string)obj[i]["category"];
        string id = (string)obj[i]["id"];

        string Message = "Test message";

        if (string.IsNullOrEmpty(Message)) return;
                    
        // Append the user's access token to the URL
        string  path=String.Format("https://graph.facebook.com/{0}",id);
                     
        var url = path+"/feed?" +
        AppendKeyvalue("access_token",AccessToken);

        // The POST body is just a collection of key=value pairs,
        // the same way a URL GET string might be formatted
        var parameters = ""
        + AppendKeyvalue("name", "name")
        + AppendKeyvalue("caption", "a test caption")
        + AppendKeyvalue("description", "test description ")
        + AppendKeyvalue("message", Message);
        // Mark this request as a POST, and write the parameters
        // to the method body (as opposed to the query string for a GET)
        var webRequest = WebRequest.Create(url);
        webRequest.ContentType = "application/x-www-form-urlencoded";
        webRequest.Method = "POST";
        byte[] bytes = System.Text.Encoding.ASCII.GetBytes(parameters);
        webRequest.ContentLength = bytes.Length;
        System.IO.Stream os = webRequest.GetRequestStream();
        os.Write(bytes, 0, bytes.Length);
        os.Close();

        // Send the request to Facebook, and query the result to get the confirmation code
        try
        {
            var webResponse = webRequest.GetResponse();
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(webResponse.GetResponseStream());
                string PostID = sr.ReadToEnd();
            }
            finally
            {
                if (sr != null) sr.Close();
            }
        }
        catch (WebException ex)
        {
            // To help with debugging, we grab
            // the exception stream to get full error details
            StreamReader errorStream = null;
            try
            {
                errorStream = new StreamReader(ex.Response.GetResponseStream());
                this.ErrorMessage = errorStream.ReadToEnd();
            }
            finally
            {
                if (errorStream != null) errorStream.Close();
            }
        }
    }
}

I used the AppendKeyvalue method to append key value pairs:

C#
public static string AppendKeyvalue(string key, string value)
{
    return string.Format("{0}={1}&", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(value));
}

The above code returns the post ID if posted successfully.

Note: Access tokens are different for different users.

That’s it. We have successfully posted a new post on a user's page. Happy coding.

License

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


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralCode is not working , Lots of errors and not proper explanation Pin
vipan.net24-Oct-17 21:36
professionalvipan.net24-Oct-17 21:36 
QuestionCreate Facebook App and Post to page from asp.net Pin
kashifjaat28-Mar-16 21:22
kashifjaat28-Mar-16 21:22 
Create Facebook App and Post to page from asp.net

In Previous Article we create a facebook app[^]
QuestionSample Code Pin
Ricard Picazzo9-Jul-15 2:48
Ricard Picazzo9-Jul-15 2:48 
AnswerRe: Sample Code Pin
pavani kadambari30-Jul-15 2:06
pavani kadambari30-Jul-15 2:06 
Questionwhat does mean by code Pin
piyush201127-Mar-14 1:27
piyush201127-Mar-14 1:27 
AnswerRe: what does mean by code Pin
pavani kadambari2-Apr-14 3:05
pavani kadambari2-Apr-14 3:05 
QuestionHow to get the access token without loging to facebook on browser? Pin
Modather Sadik31-Aug-13 4:52
Modather Sadik31-Aug-13 4:52 
AnswerRe: How to get the access token without loging to facebook on browser? Pin
pavani kadambari11-Sep-13 8:34
pavani kadambari11-Sep-13 8:34 
GeneralRe: Pin
Modather Sadik1-Oct-13 4:45
Modather Sadik1-Oct-13 4:45 
GeneralRe: Pin
pavani kadambari19-Oct-13 3:15
pavani kadambari19-Oct-13 3:15 
GeneralRe: Pin
Modather Sadik14-Nov-13 1:38
Modather Sadik14-Nov-13 1:38 
GeneralMy vote of 1 Pin
R koyee25-Feb-13 17:23
R koyee25-Feb-13 17:23 
GeneralMy vote of 1 Pin
R koyee25-Feb-13 17:22
R koyee25-Feb-13 17:22 
Questiongetting facebook pages Pin
NaniCh16-Aug-12 20:45
NaniCh16-Aug-12 20:45 
AnswerRe: getting facebook pages Pin
pavani kadambari21-Aug-12 0:55
pavani kadambari21-Aug-12 0:55 
GeneralRe: getting facebook pages Pin
NaniCh21-Aug-12 1:40
NaniCh21-Aug-12 1:40 
GeneralRe: getting facebook pages Pin
NaniCh24-Aug-12 20:01
NaniCh24-Aug-12 20:01 
Generaldoesn't getting token Pin
NaniCh7-Aug-12 0:38
NaniCh7-Aug-12 0:38 
GeneralRe: doesn't getting token Pin
pavani kadambari7-Aug-12 4:29
pavani kadambari7-Aug-12 4:29 
GeneralRe: doesn't getting token Pin
NaniCh7-Aug-12 9:03
NaniCh7-Aug-12 9:03 
GeneralRe: doesn't getting token Pin
pavani kadambari22-Aug-12 5:15
pavani kadambari22-Aug-12 5:15 
GeneralRe: doesn't getting token Pin
NaniCh22-Aug-12 19:55
NaniCh22-Aug-12 19:55 
GeneralRe: doesn't getting token Pin
pavani kadambari22-Aug-12 20:33
pavani kadambari22-Aug-12 20:33 
GeneralRe: doesn't getting token Pin
NaniCh22-Aug-12 23:03
NaniCh22-Aug-12 23:03 
GeneralRe: doesn't getting token Pin
pavani kadambari23-Aug-12 1:00
pavani kadambari23-Aug-12 1:00 

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.