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.
protected void Authorization_Click(object sender, EventArgs e)
{
string callbackUrl = "xxxxxxx";
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:
public void getpageTokens()
{
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();
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:
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;
string path=String.Format("https://graph.facebook.com/{0}",id);
var url = path+"/feed?" +
AppendKeyvalue("access_token",AccessToken);
var parameters = ""
+ AppendKeyvalue("name", "name")
+ AppendKeyvalue("caption", "a test caption")
+ AppendKeyvalue("description", "test description ")
+ AppendKeyvalue("message", Message);
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();
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)
{
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:
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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.