如何使用 SDK for .NET 获取 Facebook 用户的 ID?
Posted
技术标签:
【中文标题】如何使用 SDK for .NET 获取 Facebook 用户的 ID?【英文标题】:How to get the id of a Facebook user with the SDK for .NET? 【发布时间】:2016-11-22 18:50:47 【问题描述】:我正在使用适用于 .NET 7.0.6 的 Facebook SDK
通过这段代码,我可以获取姓名、名字、姓氏和其他属性,但不能获取用户的 ID。
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
dynamic resultMe = _fb.Get("me?fields=id");
return resultMe.id;
我怎样才能得到它?
【问题讨论】:
/me?fields=id ... 怎么样? 代码只是为了举例说明。你说的我听不懂。 在 api explorer 中运行良好:developers.facebook.com/tools/explorer/… 你调试过resultMe吗? 是的,使用 api explorer 可以正常工作。如果我使用适用于 javascript 的 SDK 执行此操作,它可以正常工作,但适用于 .NET 的 SDK 会向用户 id 抛出不同的结果,如下所示:1337210272996478 【参考方案1】:ID 是“App Scoped”,用户将获得每个应用的不同(但唯一)ID。在 API Explorer 中,您很可能没有选择您的应用程序,而只选择了官方 API Explorer 应用程序 - 当然,这会导致不同的 ID。
换句话说:您确实获得了一个 ID,它是识别回访用户的正确 ID。
【讨论】:
我已经多次使用 API Explorer,我已经编写了几行代码,但是使用 JavaScript SDK,我确定这不是我的错误。 我 100% 确定我的答案是正确的。你确实有身份证,对吧?这不像你什么都得不到。只需在 api explorer 中选择您的应用并再次拨打电话,您将获得相同的 id。【参考方案2】:HomeController.cs
using Facebook;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace FaceTest.Controllers
public class HomeController : Controller
public ActionResult Index()
ViewBag.UrlFb = GetFacebookLoginUrl();
return View();
public ActionResult About()
//ViewBag.Message = "Your application description page.";
ViewBag.Name = !String.IsNullOrEmpty(GetProfileName()) ? GetProfileName() : "Inicia Sesión";
ViewBag.Id = !String.IsNullOrEmpty(GetProfileId()) ? GetProfileId() : "Inicia Sesión";
return View();
public ActionResult Contact()
ViewBag.Message = "Your contact page.";
return View();
public string GetFacebookLoginUrl()
dynamic parameters = new ExpandoObject();
parameters.client_id = "1766341193627031";
parameters.redirect_uri = "http://localhost:51518/Home/RetornoFb/";
parameters.response_type = "code";
parameters.display = "page";
var extendedPermissions = "publish_actions";
parameters.scope = extendedPermissions;
var _fb = new FacebookClient();
var url = _fb.GetLoginUrl(parameters);
return url.ToString();
public ActionResult RetornoFb()
var _fb = new FacebookClient();
FacebookOAuthResult oauthResult;
if(!_fb.TryParseOAuthCallbackUrl(Request.Url, out oauthResult))
// Error
if (oauthResult.IsSuccess)
//Pega o Access Token "permanente"
dynamic parameters = new ExpandoObject();
parameters.client_id = "1766341193627031";
parameters.redirect_uri = "http://localhost:51518/Home/RetornoFb/";
parameters.client_secret = "52cee8ef9437e4981302c24a66e13d55";
parameters.code = oauthResult.Code;
dynamic result = _fb.Get("/oauth/access_token", parameters);
var accessToken = result.access_token;
//TODO: Guardar no banco
Session.Add("FbUserToken", accessToken);
else
// tratar
return RedirectToAction("Index");
public ActionResult DetalhesDoUsuario()
if (Session["FbuserToken"] != null)
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
//detalhes do usuario
var request = _fb.Get("me");
var a = request;
return RedirectToAction("Index");
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
/* public string GetName(string externalToken)
FacebookClient client = new FacebookClient(externalToken);
dynamic resultMe = client.Get("me?fields=id,name");
return resultMe.Name;
*/
public string GetProfileName()
if (Session["FbuserToken"] != null)
try
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
dynamic resultMe = _fb.Get("me?fields=first_name");
return resultMe.first_name;
catch (FacebookOAuthException)
return null;
return null;
public string GetProfileId()
if (Session["FbuserToken"] != null)
try
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
dynamic resultMe = _fb.Get("me?fields=id");
return resultMe.id;
catch (FacebookOAuthException)
return null;
return null;
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
/*public byte[] GetPhoto(string userId)
try
string url = "https://graph.facebook.com/" + userId +
"?fields=picture.width(720).height(720)";
WebClient webClient = new WebClient();
string response = webClient.DownloadString(url);
dynamic json = JObject.Parse(response);
string urlPicture = json.picture.data.url;
return webClient.DownloadData(urlPicture);
catch (Exception)
return null;
*/
public byte[] GetPhoto()
try
string url = "https://graph.facebook.com/" + GetProfileId() +"?fields=picture.width(480).height(480)";
WebClient webClient = new WebClient();
string response = webClient.DownloadString(url);
dynamic json = JObject.Parse(response);
string urlPicture = json.picture.data.url;
return webClient.DownloadData(urlPicture);
catch (Exception)
return null;
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
/* */
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
/*
protected IEnumerable<string> GetFriendIds(string externalToken)
FacebookClient client = new FacebookClient(externalToken);
dynamic result = client.Get("me/friends");
foreach (dynamic friend in result.data)
yield return friend.id;
*/
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
public ActionResult ListarAmigos()
if (Session["FbuserToken"] != null)
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
//listar os amigos
var request = _fb.Get("me/friends");
var a = request;
return RedirectToAction("Index");
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
/*
public void Share(string userId, string externalToken, Yipi yipi)
dynamic messagePost = new ExpandoObject();
messagePost.link = GetYipiUrl(yipi);
messagePost.message = string.Format(TextMessage, yipi.Message);
FacebookClient client = new FacebookClient(externalToken);
client.Post(userId + "/feed", messagePost);
*/
/* ------------------------------------------------------------------------------------------------------------------------------------------------ */
public ActionResult PublicarMensagem()
if (Session["FbuserToken"] != null)
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
//Postar uma mensagem na timeline
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://www.rodolfofadino.com.br/wp-content/uploads/2013/12/image_thumb10.png";
messagePost.link = "http://www.rodolfofadino.com.br/2013/12/test-mode-values-para-o-microsoft-advertising-sdk-windows-8/";
messagePost.name = "Post name...";
messagePost.caption = " Post Caption";
messagePost.description = "post description";
messagePost.message = "Mensagem de testes da aplicação";
try
var postId = _fb.Post("me/feed", messagePost);
catch (FacebookOAuthException ex)
//handle oauth exception
catch (FacebookApiException ex)
//handle facebook exception
return RedirectToAction("Index");
public ActionResult PublicarFoto()
if (Session["FbuserToken"] != null)
var _fb = new FacebookClient(Session["FbuserToken"].ToString());
//upload de imagem
FacebookMediaObject media = new FacebookMediaObject
FileName = "Nome da foto",
ContentType = "image/jpeg"
;
byte[] img = System.IO.File.ReadAllBytes(Server.MapPath("~/Content/rodolfo.jpg"));
media.SetValue(img);
dynamic parameters = new ExpandoObject();
parameters.source = media;
parameters.message = "Descricao";
try
dynamic result = _fb.Post("/me/photos", parameters);
catch (Exception ex)
return RedirectToAction("Index");
index.cshtml
@
ViewBag.Title = "Home Page";
<div class="jumbotron">
<h1>ASP.NET + Facebook</h1>
<p><a href="@ViewBag.UrlFb" class="btn btn-primary btn-large">Login Facebook</a></p>
</div>
关于.cshtml
@
ViewBag.Title = "About";
<h2>@ViewBag.Title.</h2>
<h3>@ViewBag.Name</h3>
<p>@ViewBag.Id</p>
【讨论】:
我不确定您在那里发布了什么,但这不是您问题的答案...如果您想添加代码,请改为编辑您的问题。但我很确定不需要额外的代码,请参阅我的答案。如果您需要发布代码,请仅发布相关部分。 谢谢,对不起,我是这个平台的新手。以上是关于如何使用 SDK for .NET 获取 Facebook 用户的 ID?的主要内容,如果未能解决你的问题,请参考以下文章
我想使用 HpCloud 的 Face Detect API for iphone sdk
在 ASP.Net MVC 应用程序中从 Facebook SDK for .Net 获取 Facebook 用户访问令牌
如何使用 abbyy mobile sdk for iphone 获取坐标
如何在 authorize.net sdk for android 中传递 api 登录密钥和事务 ID?