1

我在 asp.net Web 应用程序的 facebook_login 页面的 Page_Load 上使用以下代码。重定向此 url 后,我在 url 中获得了 accesstoken,但是当我尝试通过 HttpContext.Current.Request.Url.AbsoluteUri 访问此当前 url 时,它给出了发布它的应用程序的 url,而不是当前在窗口中的 url。

如何访问此访问令牌或用户详细信息?

var uriParams = new Dictionary<string, string>() {
                    {"client_id", facebookAppId},
                    {"response_type", "token"},
                    {"scope", "user_about_me, read_stream, email"},
                    {"redirect_uri", "http://apps.facebook.com/appNameHere/"}
                }; 
        StringBuilder urlBuilder = new StringBuilder();
        foreach (var current in uriParams)
        {
            if (urlBuilder.Length > 0)
            {
                urlBuilder.Append("&");
            }
            var encoded = HttpUtility.UrlEncode(current.Value);
            urlBuilder.AppendFormat("{0}={1}", current.Key, encoded);
        }
        var loginUrl = "http://www.facebook.com/dialog/oauth?" + urlBuilder.ToString();
        Response.Redirect(loginUrl);
4

1 回答 1

1

在 Facebook 中,您可以设置回调 url值,该值应指向您的 Web 应用程序。因此,一旦您向 Facebook 发出请求http://www.facebook.com/dialog/oauth并在成功登录后重定向到 Callback Url(这是您的 Web 应用程序)。

然后你必须调用 url :https://graph.facebook.com/oauth/access_token 像这样:

        StringBuilder uri = new StringBuilder();
        uri.Append("https://graph.facebook.com/oauth/access_token?");
        uri.Append("client_id=" + ClientKey + "&");
        uri.Append("redirect_uri=" + Curl + "&");
        uri.Append("scope=offline_access&");
        uri.Append("client_secret=" + ClientSecret + "&");
        uri.Append("code=" + OAuthCode);

        HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
        req.Headers.Add("Authorization", String.Empty);            
        req.Method = "POST";
        req.ServicePoint.Expect100Continue = false;
        req.ContentLength = 0;
        req.ContentType = "application/x-www-form-urlencoded";

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
            System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
            string result = sr.ReadToEnd().Trim();
            string[] resultCollection = Regex.Split(result, "&");
            string access_token = Regex.Split(resultCollection[0], "=")[1];//This is the access token
            //which you want and you can save it to database or some  where for further use.
        }
        catch (WebException ex)
        {
            resp = (HttpWebResponse)ex.Response;

            //pass on the exception
            throw ex;
        }

更新 :

OAuthCode你可以这样得到,成功登录后FB重定向到你的web应用页面后可用

OAuthCode = Request.Params["code"];

标题你可以像空一样传递String.Empty

于 2013-03-19T04:51:44.107 回答