1.本博客主要介绍如何应用facebook .net SDK,实现发帖、点赞、上传照片视频等功能,更多关于facebook API,请参考:https://developers.facebook.com

2.注册facebook账号,并且注册facebook app,参考地址:https://developers.facebook.com/apps,注册了app之后,会得到一些此app的信息,

这些信息都是要用到的。

3.注册好了App之后,开始新建解决方案(本例为asp.net mvc4 web app)

4.引入facebook .net sdk,下载地址:https://github.com/facebook-csharp-sdk/facebook-csharp-sdk,关于更多SDK文档地址:https://developers.facebook.com/docs/

除了直接下载之外,还能通过NuGet添加

5.安装完Facebook SDK,对web.config文件做点设置如下

6.一切准备就绪,现在开始使用SDK,首先登入授权,授权过程中有个scope参数,这里面是表示要授权的一些项

  1. FacebookClient fbClient = new FacebookClient();
  2. string appID = ConfigurationManager.AppSettings["AppID"];
  3. string appSecret = ConfigurationManager.AppSettings["AppSecret"];
  4. string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
  1. public ActionResult Login()
  2. {
  3. string loginUrl = "";
  4. dynamic loginResult = fbClient.GetLoginUrl(new
  5. {
  6. client_id = appID,
  7. redirect_uri = redirectUri,
  8. display = "page",
  9. scope = "email,publish_stream,read_stream"
  10. //scope = "email,publish_stream,read_stream,share_item,video_upload,photo_upload,create_note,user_friends,publish_actions,export_stream,status_update"
  11. });
  12. loginUrl = loginResult.ToString();
  13. if (!string.IsNullOrEmpty(loginUrl))
  14. return Redirect(loginUrl);
  15. else
  16. return Content("Login failed!");
  17. }

7.登入成功之后会跳转到上文提到的redirect_uri地址,而且会传回一个code值,我们用传回来的code去换取access token(这个灰常重要)

  1. public ActionResult FBMain()
  2. {
  3. string code = Request.Params["code"];
  4. string accessToken = "";
  5. if (!string.IsNullOrEmpty(code))
  6. {
  7. ///Get access token
  8. dynamic tokenResult = fbClient.Get("/oauth/access_token", new
  9. {
  10. client_id = appID,
  11. client_secret = appSecret,
  12. redirect_uri = redirectUri,
  13. code = code
  14. });
  15. accessToken = tokenResult.access_token.ToString();
  16. ViewBag.Message = "Get token successful!The token value:" + accessToken;
  17. }
  18. else
  19. {
  20. ViewBag.Message = "faield to get token!";
  21. }
  22. return View();
  23. }

8.拿到access token之后,就可以用它做很多事情了,例如发状态上传照片

a.发状态

  1. /// <summary>
  2. ///Post a news feed
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <param name="status">the text message</param>
  6. /// <date>2013/10/25, 17:09:49</date>
  7. /// <returns>a posted ID</returns>
  8. public string Post(string status)
  9. {
  10. string id = null;
  11.  
  12. try
  13. {
  14. if (!string.IsNullOrEmpty(accessToken))
  15. {
  16. FacebookClient fbClient = new FacebookClient(accessToken);
  17. dynamic postResult = fbClient.Post("/me/feed", new
  18. {
  19. message = status
  20. });
  21. id = postResult.id.ToString();
  22. }
  23. else
  24. errorMessage = ErrorTokenMessage;
  25. }
  26. catch (FacebookApiException fbex)
  27. {
  28. errorMessage = fbex.Message;
  29. }
  30.  
  31. return id;
  32. }

b.发链接

  1. /// <summary>
  2. ///share a feed
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <date>2013/10/29, 09:46:08</date>
  6. /// <param name="status">the text message</param>
  7. /// <param name="link">an valid link(eg: http://www.mojikan.com)</param>
  8. /// valid tools:https://developers.facebook.com/tools/debug
  9. /// <returns>return a post id</returns>
  10. public string Share(string status, string link)
  11. {
  12. string shareID = null;
  13. try
  14. {
  15. if (!string.IsNullOrEmpty(accessToken))
  16. {
  17. FacebookClient fbClient = new FacebookClient(accessToken);
  18. dynamic shareResult = fbClient.Post("me/feed", new
  19. {
  20. message = status,
  21. link = link
  22. });
  23. shareID = shareResult.id;
  24. }
  25. else
  26. errorMessage = ErrorTokenMessage;
  27. }
  28. catch (FacebookApiException fbex)
  29. {
  30. errorMessage = fbex.Message;
  31. }
  32. return shareID;
  33. }

c.传照片

  1. /// <summary>
  2. ///upload picture
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <param name="status">the text message</param>
  6. /// <param name="path">the picture's path</param>
  7. /// <date>2013/10/31, 15:24:51</date>
  8. /// <returns>picture id & post id</returns>
  9. public string PostPicture(String status, String path)
  10. {
  11. string result = null;
  12. try
  13. {
  14. if (!string.IsNullOrEmpty(accessToken))
  15. {
  16. FacebookClient fbClient = new FacebookClient(accessToken);
  17. using (var stream = File.OpenRead(path))
  18. {
  19. dynamic pictureResult = fbClient.Post("me/photos",
  20. new
  21. {
  22. message = status,
  23. source = new FacebookMediaStream
  24. {
  25. ContentType = "image/jpg",
  26. FileName = Path.GetFileName(path)
  27. }.SetValue(stream)
  28. });
  29. if (pictureResult != null)
  30. result = pictureResult.ToString();
  31. }
  32. }
  33. else
  34. errorMessage = ErrorTokenMessage;
  35. }
  36. catch (FacebookApiException fbex)
  37. {
  38. errorMessage = fbex.Message;
  39. }
  40. return result;
  41. }

d.传视频

  1. /// <summary>
  2. ///upload video
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <param name="status">the text message</param>
  6. /// <param name="path">the video's path</param>
  7. /// <date>2013/10/31, 15:26:40</date>
  8. /// <returns>an video id</returns>
  9. //The aspect ratio of the video must be between 9x16 and 16x9, and the video cannot exceed 1024MB or 180 minutes in length.
  10. public string PostVideo(String status, String path)
  11. {
  12. string result = null;
  13. try
  14. {
  15. if (!string.IsNullOrEmpty(accessToken))
  16. {
  17. FacebookClient fbClient = new FacebookClient(accessToken);
  18. Stream stream = File.OpenRead(path);
  19. FacebookMediaStream medStream = new FacebookMediaStream
  20. {
  21. ContentType = "video/mp4",
  22. FileName = Path.GetFileName(path)
  23. }.SetValue(stream);
  24.  
  25. dynamic videoResult = fbClient.Post("me/videos",
  26. new
  27. {
  28. description = status,
  29. source = medStream
  30. });
  31. if (videoResult != null)
  32. result = videoResult.ToString();
  33. }
  34. else
  35. errorMessage = ErrorTokenMessage;
  36. }
  37. catch (FacebookApiException fbex)
  38. {
  39. errorMessage = fbex.Message;
  40. }
  41. return result;
  42. }

e.点赞

  1. /// <summary>
  2. ///likes a news feed
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <param name="postID">a post id</param>
  6. /// <returns>return a bool value</returns>
  7. /// <date>2013/10/25, 18:35:51</date>
  8. public bool Like(string postID)
  9. {
  10. bool result = false;
  11. try
  12. {
  13. if (!string.IsNullOrEmpty(accessToken))
  14. {
  15. FacebookClient fbClient = new FacebookClient(accessToken);
  16. dynamic likeResult = fbClient.Post("/" + postID + "/likes", new
  17. {
  18. //post_id = postID,
  19. });
  20. result = Convert.ToBoolean(likeResult);
  21. }
  22. else
  23. errorMessage = ErrorTokenMessage;
  24. }
  25. catch (FacebookApiException fbex)
  26. {
  27. errorMessage = fbex.Message;
  28. }
  29. return result;
  30. }

f.发送App邀请

  1. /// <summary>
  2. ///send a app request to the user.
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <param name="status">the request message</param>
  6. /// <returns>return app object ids & user ids</returns>
  7. /// <date>2013/10/28, 09:33:35</date>
  8. public string AppRequest(string userID, string status)
  9. {
  10. string result = null;
  11. try
  12. {
  13. string appToken = this.GetAppAccessToken();
  14. if (!string.IsNullOrEmpty(appToken))
  15. {
  16. FacebookClient fbClient = new FacebookClient(appToken);
  17. dynamic requestResult = fbClient.Post(userID + "/apprequests", new
  18. {
  19. message = status
  20. });
  21. result = requestResult.ToString();
  22. }
  23. else
  24. errorMessage = ErrorTokenMessage;
  25. }
  26. catch (FacebookApiException fbex)
  27. {
  28. errorMessage = fbex.Message;
  29. }
  30. return result;
  31. }
  32.  
  33. /// <summary>
  34. ///Get an app access token
  35. /// </summary>
  36. /// <author>Johnny</author>
  37. /// <date>2013/11/05, 11:52:37</date>
  38. private string GetAppAccessToken()
  39. {
  40. string appToken = null;
  41. try
  42. {
  43. FacebookClient client = new FacebookClient();
  44. dynamic token = client.Get("/oauth/access_token", new
  45. {
  46. client_id = appID,
  47. client_secret = appSecret,
  48. grant_type = "client_credentials"
  49. });
  50.  
  51. appToken = token.access_token.ToString();
  52. }
  53. catch (FacebookApiException fbex)
  54. {
  55. errorMessage = fbex.Message;
  56. }
  57. return appToken;
  58. }

g.获取状态列表

  1. /// <summary>
  2. ///get current user's post list
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <returns>return post list</returns>
  6. /// <date>2013/10/30, 13:42:37</date>
  7. public List<Post> GetPostList()
  8. {
  9. List<Post> postList = null;
  10. try
  11. {
  12. if (!string.IsNullOrEmpty(accessToken))
  13. {
  14. FacebookClient fbClient = new FacebookClient(accessToken);
  15. dynamic postResult = (IDictionary<string, object>)fbClient.Get("/me/feed");
  16. postList = new List<Post>();
  17. postList = GeneralPostList(postResult);
  18. }
  19. else
  20. errorMessage = ErrorTokenMessage;
  21. }
  22. catch (FacebookApiException fbex)
  23. {
  24. errorMessage = fbex.Message;
  25. }
  26. return postList;
  27. }
  28.  
  29. /// <summary>
  30. ///get one user's post list
  31. /// </summary>
  32. /// <param name="userID">user id</param>
  33. /// <returns>return post list</returns>
  34. /// <author>Johnny</author>
  35. /// <date>2013/11/06, 17:06:19</date>
  36. public List<Post> GetPostList(string userID)
  37. {
  38. List<Post> postList = null;
  39. try
  40. {
  41. if (!string.IsNullOrEmpty(accessToken))
  42. {
  43. FacebookClient fbClient = new FacebookClient(accessToken);
  44. postList = new List<Post>();
  45. dynamic postResult = (IDictionary<string, object>)fbClient.Get("/" + userID + "/feed");
  46. postList = GeneralPostList(postResult);
  47. }
  48. else
  49. errorMessage = ErrorTokenMessage;
  50. }
  51. catch (FacebookApiException fbex)
  52. {
  53. errorMessage = fbex.Message;
  54. }
  55. return postList;
  56. }
  57.  
  58. private List<Post> GeneralPostList(dynamic postResult)
  59. {
  60. List<Post> postList = null;
  61. try
  62. {
  63. postList = new List<Post>();
  64. foreach (var item in postResult.data)
  65. {
  66. Dictionary<string, object>.KeyCollection keys = item.Keys;
  67. Post post = new Post();
  68.  
  69. List<Action> actionList = new List<Action>();
  70. dynamic actions = item.actions;
  71. if (actions != null)
  72. {
  73. foreach (var ac in actions)
  74. {
  75. Action action = new Action();
  76. action.link = ac.link.ToString();
  77. action.name = ac.name.ToString();
  78.  
  79. actionList.Add(action);
  80. }
  81. post.Actions = actionList;
  82. }
  83.  
  84. if (keys.Contains<string>("caption"))
  85. post.Caption = item.caption.ToString();
  86. if (keys.Contains<string>("created_time"))
  87. post.CreatedTime = item.created_time.ToString();
  88. if (keys.Contains<string>("description"))
  89. post.Description = item.description.ToString();
  90.  
  91. if (keys.Contains<string>("from"))
  92. {
  93. FromUser fUser = new FromUser();
  94. fUser.ID = item.from.id.ToString();
  95. fUser.Name = item.from.name.ToString();
  96. post.From = fUser;
  97. }
  98.  
  99. if (keys.Contains<string>("icon"))
  100. post.Icon = item.icon.ToString();
  101.  
  102. post.ID = item.id.ToString();
  103.  
  104. if (keys.Contains<string>("include_hidden"))
  105. post.IncludeHidden = item.include_hidden.ToString();
  106.  
  107. if (keys.Contains<string>("link"))
  108. post.Link = item.link.ToString();
  109.  
  110. if (keys.Contains<string>("message"))
  111. post.Message = item.message.ToString();
  112.  
  113. if (keys.Contains<string>("picture"))
  114. post.Picture = item.picture.ToString();
  115.  
  116. if (keys.Contains<string>("name"))
  117. post.Name = item.name.ToString();
  118.  
  119. if (keys.Contains<string>("object_id"))
  120. post.ObjectID = item.object_id.ToString();
  121.  
  122. if (keys.Contains<string>("privacy"))
  123. post.Privacy = item.privacy.ToString();
  124.  
  125. if (keys.Contains<string>("shares"))
  126. post.Shares = item.shares.ToString();
  127.  
  128. if (keys.Contains<string>("source"))
  129. post.Source = item.source.ToString();
  130.  
  131. if (keys.Contains<string>("status_type"))
  132. post.StatusType = item.status_type.ToString();
  133.  
  134. if (keys.Contains<string>("story"))
  135. post.Story = item.story.ToString();
  136.  
  137. if (keys.Contains<string>("type"))
  138. post.Type = item.type.ToString();
  139.  
  140. if (keys.Contains<string>("updated_time"))
  141. post.UpdatedTime = item.updated_time.ToString();
  142.  
  143. postList.Add(post);
  144. }
  145. }
  146. catch (FacebookApiException fbex)
  147. {
  148. errorMessage = fbex.Message;
  149. }
  150. return postList;
  151. }

h.获取个人用户信息和朋友信息

  1. /// <summary>
  2. ///Get the current user info
  3. /// </summary>
  4. /// <author>Johnny</author>
  5. /// <returns>return an UserInfo</returns>
  6. /// <date>2013/10/29, 13:36:07</date>
  7. public UserInfo GetUserInfo()
  8. {
  9. UserInfo userInfo = null;
  10. try
  11. {
  12. if (!string.IsNullOrEmpty(accessToken))
  13. {
  14. FacebookClient fbClient = new FacebookClient(accessToken);
  15. dynamic user = fbClient.Get("/me");
  16. Dictionary<string, object>.KeyCollection keys = user.Keys;
  17. userInfo = new UserInfo();
  18. userInfo.ID = user.id.ToString();
  19. if (keys.Contains<string>("name"))
  20. userInfo.Name = user.name.ToString();
  21. if (keys.Contains<string>("first_name"))
  22. userInfo.FirstName = user.first_name.ToString();
  23. if (keys.Contains<string>("last_name"))
  24. userInfo.LastName = user.last_name.ToString();
  25. if (keys.Contains<string>("username"))
  26. userInfo.UserName = user.username.ToString();
  27. if (keys.Contains<string>("link"))
  28. userInfo.Link = user.link.ToString();
  29. if (keys.Contains<string>("timezone"))
  30. userInfo.TimeZone = user.timezone.ToString();
  31. if (keys.Contains<string>("updated_time"))
  32. userInfo.UpdatedTime = Convert.ToDateTime(user.updated_time);
  33. if (keys.Contains<string>("verified"))
  34. userInfo.Verified = user.verified.ToString();
  35. if (keys.Contains<string>("gender"))
  36. userInfo.Gender = user.gender.ToString();
  37. }
  38. else
  39. errorMessage = ErrorTokenMessage;
  40. }
  41. catch (FacebookApiException fbex)
  42. {
  43. errorMessage = fbex.Message;
  44. }
  45. return userInfo;
  46. }
  47.  
  48. /// <summary>
  49. ///get friends info
  50. /// </summary>
  51. /// <author>Johnny</author>
  52. /// <returns>return list of UserInfo</returns>
  53. /// <date>2013/10/31, 15:57:40</date>
  54. public List<UserInfo> GetFriendInfoList()
  55. {
  56. List<UserInfo> userList = null;
  57. try
  58. {
  59. if (!string.IsNullOrEmpty(accessToken))
  60. {
  61. FacebookClient fbClient = new FacebookClient(accessToken);
  62. dynamic friends = fbClient.Get("/me/friends");
  63. if (friends != null)
  64. {
  65. userList = new List<UserInfo>();
  66. foreach (dynamic item in friends.data)
  67. {
  68. UserInfo user = new UserInfo();
  69. user.ID = item.id.ToString();
  70. user.Name = item.name.ToString();
  71.  
  72. userList.Add(user);
  73. }
  74. }
  75. }
  76. else
  77. errorMessage = ErrorTokenMessage;
  78. }
  79. catch (FacebookApiException fbex)
  80. {
  81. errorMessage = fbex.Message;
  82. }
  83. return userList;
  84. }

以上就是一些常用的API。

关于facebook翻墙,请参考这里进行设置,http://www.i7086.com/gugeyingyonggoagentrangninziyoufangwenwangluotuwenjiaocheng

如设置成功,可以通过谷歌浏览器顺利打开facebook网站,关于证书导入:http://jingyan.baidu.com/article/ca00d56caf98d3e99eebcf16.html

配置好了goagent,打开它,然后用谷歌浏览器就可以顺利打开facebook,youtobe等网站了,如果要通过IE打开,则改一下设置就行了,谷歌和IE都能开。

应用facebook .net sdk的更多相关文章

  1. 浅谈 facebook .net sdk 应用

    今天看了一篇非常好的文章,就放在这里与大家分享一下,顺便也给自己留一份.这段时间一直在学习MVC,另外如果大家有什么好的建议或者学习的地方,也请告知一下,谢谢. 这篇主要介绍如何应用facebook ...

  2. 使用Facebook的SDK判斷來訪者是否已經按讃并成為本站粉絲團的成員

    今天公司裡要做活動,其中有一項活動內容是要求來訪者按一下facebook粉絲團的讃,按了讃之後贈送現金.Facebook被墻大家眾所周知,在百度搜了一下發現因為被墻的原因導致國內涉及到Facebook ...

  3. facebook .net sdk 应用

    浅谈 facebook .net sdk 应用   今天看了一篇非常好的文章,就放在这里与大家分享一下,顺便也给自己留一份.这段时间一直在学习MVC,另外如果大家有什么好的建议或者学习的地方,也请告知 ...

  4. 零基础图文傻瓜教程接入Facebook的sdk

    零基础图文傻瓜教程接入Facebook的sdk 本人视频教程系类   iOS中CALayer的使用 0. 先解决你的 VPN FQ上外网问题,亲,解决这一步才能进行后续操作^_^. 1. 点击右侧链接 ...

  5. 手游服务器端接入facebook的SDK

    手游如果支持facebook登录,就要接入facebook的登录SDK.刚好工作中自己做了这一块的接入功能现在记录分享下来提供一个参考. 当前只是接入了登录这个功能,先简单的说说接入facebook登 ...

  6. 在Android上实现使用Facebook登录(基于Facebook SDK 3.5)

    准备工作: 1.       Facebook帐号,国内开发者需要一个vpn帐号(网页可以浏览,手机可以访问) 2.       使用Facebook的SDK做应用需要一个Key Hashes值. 2 ...

  7. 分享前端Facebook及Twitter第三方登录

    最近公司要求做海外的第三方登录:目前只做了Facebook和Twitter;国内百度到的信息太少VPN FQ百度+Google了很久终于弄好了.但是做第三方登录基本上都有个特点就是引入必须的js,设置 ...

  8. Android Facebook和Twitter分享

    1. 背景 在年初的时候,公司的项目有个新的需求,在英文版的应用中加入Facebook和Twitter分享功能. 2. 完成情况 由于这个项目比较急,所以开发这个功能从预研到接入总共耗时一周.后来,在 ...

  9. Facebook

    Facebook登录为iOS Facebook的SDK为iOS提供了各种登录的经验,你的应用程序可以使用它来 ​​验证一个人.这份文件包括了所有你需要知道,以落实Facebook登录在你的iOS应用程 ...

随机推荐

  1. 2014年最新的辛星html、css教程打包公布了,免积分,纯PDF(还有PHP奥)

    首先说一下,这个教程是我的全部的博客的精华,我整理了两天之后才做出的这个pdf文档,累死我了,以下免积分给大家,希望大家可以不吝指正,提出它的一些不足什么的,谢谢啦: 以下就是它的下载地址了:2014 ...

  2. 从头开始学JavaScript 笔记(一)——基础中的基础

    原文:从头开始学JavaScript 笔记(一)--基础中的基础 概要:javascript的组成. 各个组成部分的作用 . 一.javascript的组成   javascript   ECMASc ...

  3. JavaWeb显示器

    本文研究的总结.欢迎转载,但请注明出处:http://blog.csdn.net/pistolove/article/details/44310967 A:监听器的定义      专门用于其它对象身上 ...

  4. 如此高效通用的分页存储过程是带有sql注入漏洞的

    原文:如此高效通用的分页存储过程是带有sql注入漏洞的 在google中搜索“分页存储过程”会出来好多结果,是大家常用的分页存储过程,今天我却要说它是有漏洞的,而且漏洞无法通过修改存储过程进行补救,如 ...

  5. C#中实现WebBrowser控件的HTML源代码读写

    原文:C#中实现WebBrowser控件的HTML源代码读写 C#中实现WebBrowser控件的HTML源代码读写http://www.blogcn.com/user8/flier_lu/index ...

  6. iOS开发的一些奇巧淫技2

    能不能只用一个pan手势来代替UISwipegesture的各个方向? - (void)pan:(UIPanGestureRecognizer *)sender { typedef NS_ENUM(N ...

  7. ultraEdit-32 PHP/HTML智能提示

    原文 ultraEdit-32 PHP/HTML智能提示 高级–>配置–>编辑器–>自动完成–>勾选自动显示……选项,在下面输入框中输入你要求输出多个字符才出现提示,比如 ec ...

  8. c语言发挥帕斯卡三角

    我们已经确定了帕斯卡三角的规则,下面是我的代码,非常实用哦! !! #include<stdio.h>  void main()  {      int i,j,n,k;      sca ...

  9. 《java系统性能优化》--2.高速缓存

    上一节.简介了怎样发现性能瓶颈.从这节開始.我会和大家分享我在项目中做的一些性能调优工作.这个系列没有什么顺序可言,认为什么重要.就说说什么. 这节.我们聊缓存. 最開始接触缓存这个词,是学习硬件知识 ...

  10. POJ 3390 Print Words in Lines(DP)

    Print Words in Lines Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 1624 Accepted: 864 D ...