facebook-C#-sdk MVC “Hello World” app - how to get access token?

拜拜、爱过 提交于 2019-12-20 10:24:13

问题


I've downloaded the C# Facebook SDK "Simple MVC Website Example" from CodePlex at:

http://facebooksdk.codeplex.com/releases/view/54371

and have successfully got it to authenticate to my test Facebook app. But I can't quite work out how to get the access token (and I'm going to want offline access, so I only need to grab that token once, when the user first authorizes my app to grab their feed data).

Many thanks


回答1:


You will want to do two things. First, to request offline_access, you need to change the Javascript login function to request offline access as follows. This is in the Views/Home/Index.aspx.

    <div id="fb-root"></div>
    <script src="http://connect.facebook.net/en_US/all.js"></script>
    <script>
        FB.init({ appId: '<%:FacebookSettings.Current.AppId %>', status: true, cookie: true, xfbml: true });
        $('#fbLogin').click(function() {
            FB.login(function (response) {
                if (response.session) {
                    window.location = '<%:Url.Action("Profile") %>'
                } else {
                    // user cancelled login
                }
            }, { perms: 'offline_access' });
        });
    </script>
</asp:Content>    

Next, to get the access token, you just do the following in action after the user is authenticated:

    public ActionResult Profile()
    {
        var app = new FacebookApp();
        if (app.Session == null)
        {
            // The user isnt logged in to Facebook
            // send them to the home page
            return RedirectToAction("Index");
        }
    // Read current access token:
        var accessToken = app.Session.AccessToken;

        // Get the user info from the Graph API
        dynamic me = app.Api("/me");
        ViewData["FirstName"] = me.first_name;
        ViewData["LastName"] = me.last_name;

        return View();
    }



回答2:


My recommendation is that you work with the new graph api instead, you can get it here

http://github.com/facebook/csharp-sdk

here's a description on how you fetch the authentication token:

http://developers.facebook.com/docs/authentication/



来源:https://stackoverflow.com/questions/4227964/facebook-c-sdk-mvc-hello-world-app-how-to-get-access-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!