skip to Main Content

I already have authenticated users in OAuth. I have my app-id, my access token which I extended. Facebook recently updated their Graph Api to v3.1. I have searched all over the net but no luck. How can i get the post in my Create-Post controller to save both to my database and post to facebook as well. Posting as a page or post to user wall examples would be great, in ASP.NET Core MVC Please.

I have tried everything on the web but nothing works. I have removed the edits on my post controller so it can only store the user-post to my database for now. Please help, how can I tackle this problem good people.

//post create post
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Post post)
        {
            string url = "http://graph.facebook.com/v3.1/";
            string myAppID = "my_app_id";
            string myAccessToken = "my_access_token";


            if (ModelState.IsValid)
            {
                _db.Add(post);
                await _db.SaveChangesAsync();


                return RedirectToAction(nameof(Index), new { userId = post.UserId });
            }
            return View(post);

2

Answers


  1. Chosen as BEST ANSWER

    Good-day fellow developers. In case any of you out there are still experiencing problems posting to Facebook from your .NET Core 2.0 applications here is the solution.

    First of all, the documentation from Facebook is very misleading(for myself it was). It turns out that the actual access token you need is the Page Access Token. You do not need app access token/user access token when doing queries to the API all you need is the page access token. This of-course works only if you are the Application and page admin no need for App Review at this point. I hope you figure out how to extend this access token to never expire here

    public class FacebookController : Controller
    {
        readonly string _accessToken;
        readonly string _pageID;
        readonly string _facebookAPI = "https://graph.facebook.com/";
        readonly string _pageEdgeFeed = "feed";
    
        public FacebookController(string accessToken, string pageID)
        {
            _accessToken = accessToken;
            _pageID = pageID;
            _postToPageURL = $"{_facebookAPI}{pageID}/{_pageEdgeFeed}";
        }
        // Publish a simple text post
        public async Task<Tuple<int,string>> PublishPost(string postText)
        {
            using (var http = new HttpClient())
            {
                var postData = new Dictionary<string, string>
                {
                    {"access_token", _accessToken },
                    {"message", postText }
                };
    
                var httpResponse = await http.PostAsync(
                    _postToPageURL,
                    new FormUrlEncodedContent(postData));
                var httpContent = await httpResponse.Content.ReadAsStringAsync();
    
                return new Tuple<int, string>(
                        (int)httpResponse.StatusCode,
                        httpContent
                    );
            }
        }
    

    This is how you use it on your controller:

    //declare your strings, I stored them in a class
    public static class FacebookSettings
        {
            public static string pageID = "Your-Page-Id";
            public static string Access_Token = "Your-Page-Access-Token";
        }
        //post create post
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(Post post)
        {
            if (ModelState.IsValid)
            {
            //here you pass in your parameters
            var facebook = new 
            FacebookController
            (
                FacebookSettings.Access_Token,
                FacebookSettings.pageID
            );
            var simpleText = Task.Run(async () =>
            {
             using (var http = new HttpClient())
                 {
                     return await facebook.PublishSimplePost(post.UserPost);
                 }
             });
             //Debug your application to check if you get the correct id here:
             var simpleTextJson = JObject.Parse(simpleText.Result.Item2);
    
                _db.Add(post);
                await _db.SaveChangesAsync();
                return RedirectToAction(nameof(Index), new { userId = post.UserId });
            }
            return View(post);
    

  2. I also had the same problem after my website was not approved to publish_pages on Facebook.

    I would recommend that you try using a javascript SDK to do that, it helped me while I was facing difficulties with .NET-core. This link might help you:

    https://developers.facebook.com/docs/javascript/quickstart

    <script>
      window.fbAsyncInit = function() {
        FB.init({
          appId            : 'your-app-id',
          autoLogAppEvents : true,
          xfbml            : true,
          version          : 'v3.1'
        });
      };
    
      (function(d, s, id){
         var js, fjs = d.getElementsByTagName(s)[0];
         if (d.getElementById(id)) {return;}
         js = d.createElement(s); js.id = id;
         js.src = "https://connect.facebook.net/en_US/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));
    </script>

    This will be just for loading of the SDK, you will still need a getInfo function and a post function. This how I did it, try it and see how it goes. All the best.

    <script>
    var access;
    		function getInfo(){
    			FB.api('/me','GET',{fields: 'id,name,email'},
    			function(response){
    				document.getElementById('status').innerHTML = response.email;
    				
    				access = document.getElementById('mapping').innerHTML = response.id;
    				return access;
    			});
    		}
    		
    		
    		
    		function post(){
    			var x = {	message : document.getElementById('textinput').value,
    						access_token : access};
    			FB.api('/me/feed','POST',x,
    				function(response){
    					document.getElementById('testing').innerHTML = x.message;
    				});
    		}
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search