Error getting an access token for c# webforms using facebook c# sdk
-
25-10-2019 - |
Question
I've searched through atleast 100 hundred access token issues but have not found an solution for my issue. I am using the facebook sdk to auth but when I try to simple .Get on "me" it errors out with this error: "(OAuthException) An active access token must be used to query information about the current user." I am using .NET 3.5 framework so I can not use 'dynamic'. When I substitute a valid id where "me" it works and shows the name. When I try to post to feed I get the "(OAuthException) (#200) The user hasn't authorized the application to perform this action." Any help would be great. Thanks.
Here is my code:
var webRequest = (HttpWebRequest)HttpWebRequest.Create("https://graph.facebook.com/oauth/access_token");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
var requestString = "client_id=[appid]&client_secret=[secret]&redirect_uri=http%3A%2F%2Fwww.website.com&grant_type=client_credentials&scope=publish_stream,read_stream,offline_access";
byte[] bytedata = Encoding.UTF8.GetBytes(requestString);
webRequest.ContentLength = bytedata.Length;
var requestStream = webRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
var response = webRequest.GetResponse();
var responseStream = new StreamReader(response.GetResponseStream());
var responseString = responseStream.ReadToEnd();
responseStream.Close();
response.Close();
if (!String.IsNullOrEmpty(responseString))
{
var accessToken = responseString.Replace("access_token=", "");
var fb = new FacebookWebClient(accessToken.ToString());
var me = fb.Get<FBUser>("100000219214008");
string firstName = me.name;
var postparameters = new Dictionary<string, object>();
postparameters["message"] = "Hello world!";
postparameters["name"] = "This is a name";
postparameters["link"] = "http://thisisalink.com";
postparameters["description"] = "This is a description";
var result = fb.Post("/100000219214008/feed", postparameters);
Response.Write (firstName.ToString());
}
Solution
After struggling for days with the Facebook C# SDK, I chose to go with the Facebook Javascript SDK. This SDK has wide support, examples and documentation although it is client-side. It just works.