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参数,这里面是表示要授权的一些项

FacebookClient fbClient = new FacebookClient();
string appID = ConfigurationManager.AppSettings["AppID"];
string appSecret = ConfigurationManager.AppSettings["AppSecret"];
string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
public ActionResult Login()
{
string loginUrl = "";
dynamic loginResult = fbClient.GetLoginUrl(new
{
client_id = appID,
redirect_uri = redirectUri,
display = "page",
scope = "email,publish_stream,read_stream"
//scope = "email,publish_stream,read_stream,share_item,video_upload,photo_upload,create_note,user_friends,publish_actions,export_stream,status_update"
});
loginUrl = loginResult.ToString();
if (!string.IsNullOrEmpty(loginUrl))
return Redirect(loginUrl);
else
return Content("Login failed!");
}

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

public ActionResult FBMain()
{
string code = Request.Params["code"];
string accessToken = "";
if (!string.IsNullOrEmpty(code))
{
///Get access token
dynamic tokenResult = fbClient.Get("/oauth/access_token", new
{
client_id = appID,
client_secret = appSecret,
redirect_uri = redirectUri,
code = code
});
accessToken = tokenResult.access_token.ToString();
ViewBag.Message = "Get token successful!The token value:" + accessToken;
}
else
{
ViewBag.Message = "faield to get token!";
}
return View();
}

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

a.发状态

/// <summary>
///Post a news feed
/// </summary>
/// <author>Johnny</author>
/// <param name="status">the text message</param>
/// <date>2013/10/25, 17:09:49</date>
/// <returns>a posted ID</returns>
public string Post(string status)
{
string id = null; try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic postResult = fbClient.Post("/me/feed", new
{
message = status
});
id = postResult.id.ToString();
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
} return id;
}

b.发链接

/// <summary>
///share a feed
/// </summary>
/// <author>Johnny</author>
/// <date>2013/10/29, 09:46:08</date>
/// <param name="status">the text message</param>
/// <param name="link">an valid link(eg: http://www.mojikan.com)</param>
/// valid tools:https://developers.facebook.com/tools/debug
/// <returns>return a post id</returns>
public string Share(string status, string link)
{
string shareID = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic shareResult = fbClient.Post("me/feed", new
{
message = status,
link = link
});
shareID = shareResult.id;
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return shareID;
}

c.传照片

/// <summary>
///upload picture
/// </summary>
/// <author>Johnny</author>
/// <param name="status">the text message</param>
/// <param name="path">the picture's path</param>
/// <date>2013/10/31, 15:24:51</date>
/// <returns>picture id & post id</returns>
public string PostPicture(String status, String path)
{
string result = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
using (var stream = File.OpenRead(path))
{
dynamic pictureResult = fbClient.Post("me/photos",
new
{
message = status,
source = new FacebookMediaStream
{
ContentType = "image/jpg",
FileName = Path.GetFileName(path)
}.SetValue(stream)
});
if (pictureResult != null)
result = pictureResult.ToString();
}
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return result;
}

d.传视频

/// <summary>
///upload video
/// </summary>
/// <author>Johnny</author>
/// <param name="status">the text message</param>
/// <param name="path">the video's path</param>
/// <date>2013/10/31, 15:26:40</date>
/// <returns>an video id</returns>
//The aspect ratio of the video must be between 9x16 and 16x9, and the video cannot exceed 1024MB or 180 minutes in length.
public string PostVideo(String status, String path)
{
string result = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
Stream stream = File.OpenRead(path);
FacebookMediaStream medStream = new FacebookMediaStream
{
ContentType = "video/mp4",
FileName = Path.GetFileName(path)
}.SetValue(stream); dynamic videoResult = fbClient.Post("me/videos",
new
{
description = status,
source = medStream
});
if (videoResult != null)
result = videoResult.ToString();
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return result;
}

e.点赞

/// <summary>
///likes a news feed
/// </summary>
/// <author>Johnny</author>
/// <param name="postID">a post id</param>
/// <returns>return a bool value</returns>
/// <date>2013/10/25, 18:35:51</date>
public bool Like(string postID)
{
bool result = false;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic likeResult = fbClient.Post("/" + postID + "/likes", new
{
//post_id = postID,
});
result = Convert.ToBoolean(likeResult);
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return result;
}

f.发送App邀请

        /// <summary>
///send a app request to the user.
/// </summary>
/// <author>Johnny</author>
/// <param name="status">the request message</param>
/// <returns>return app object ids & user ids</returns>
/// <date>2013/10/28, 09:33:35</date>
public string AppRequest(string userID, string status)
{
string result = null;
try
{
string appToken = this.GetAppAccessToken();
if (!string.IsNullOrEmpty(appToken))
{
FacebookClient fbClient = new FacebookClient(appToken);
dynamic requestResult = fbClient.Post(userID + "/apprequests", new
{
message = status
});
result = requestResult.ToString();
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return result;
} /// <summary>
///Get an app access token
/// </summary>
/// <author>Johnny</author>
/// <date>2013/11/05, 11:52:37</date>
private string GetAppAccessToken()
{
string appToken = null;
try
{
FacebookClient client = new FacebookClient();
dynamic token = client.Get("/oauth/access_token", new
{
client_id = appID,
client_secret = appSecret,
grant_type = "client_credentials"
}); appToken = token.access_token.ToString();
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return appToken;
}

g.获取状态列表

/// <summary>
///get current user's post list
/// </summary>
/// <author>Johnny</author>
/// <returns>return post list</returns>
/// <date>2013/10/30, 13:42:37</date>
public List<Post> GetPostList()
{
List<Post> postList = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic postResult = (IDictionary<string, object>)fbClient.Get("/me/feed");
postList = new List<Post>();
postList = GeneralPostList(postResult);
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return postList;
} /// <summary>
///get one user's post list
/// </summary>
/// <param name="userID">user id</param>
/// <returns>return post list</returns>
/// <author>Johnny</author>
/// <date>2013/11/06, 17:06:19</date>
public List<Post> GetPostList(string userID)
{
List<Post> postList = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
postList = new List<Post>();
dynamic postResult = (IDictionary<string, object>)fbClient.Get("/" + userID + "/feed");
postList = GeneralPostList(postResult);
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return postList;
} private List<Post> GeneralPostList(dynamic postResult)
{
List<Post> postList = null;
try
{
postList = new List<Post>();
foreach (var item in postResult.data)
{
Dictionary<string, object>.KeyCollection keys = item.Keys;
Post post = new Post(); List<Action> actionList = new List<Action>();
dynamic actions = item.actions;
if (actions != null)
{
foreach (var ac in actions)
{
Action action = new Action();
action.link = ac.link.ToString();
action.name = ac.name.ToString(); actionList.Add(action);
}
post.Actions = actionList;
} if (keys.Contains<string>("caption"))
post.Caption = item.caption.ToString();
if (keys.Contains<string>("created_time"))
post.CreatedTime = item.created_time.ToString();
if (keys.Contains<string>("description"))
post.Description = item.description.ToString(); if (keys.Contains<string>("from"))
{
FromUser fUser = new FromUser();
fUser.ID = item.from.id.ToString();
fUser.Name = item.from.name.ToString();
post.From = fUser;
} if (keys.Contains<string>("icon"))
post.Icon = item.icon.ToString(); post.ID = item.id.ToString(); if (keys.Contains<string>("include_hidden"))
post.IncludeHidden = item.include_hidden.ToString(); if (keys.Contains<string>("link"))
post.Link = item.link.ToString(); if (keys.Contains<string>("message"))
post.Message = item.message.ToString(); if (keys.Contains<string>("picture"))
post.Picture = item.picture.ToString(); if (keys.Contains<string>("name"))
post.Name = item.name.ToString(); if (keys.Contains<string>("object_id"))
post.ObjectID = item.object_id.ToString(); if (keys.Contains<string>("privacy"))
post.Privacy = item.privacy.ToString(); if (keys.Contains<string>("shares"))
post.Shares = item.shares.ToString(); if (keys.Contains<string>("source"))
post.Source = item.source.ToString(); if (keys.Contains<string>("status_type"))
post.StatusType = item.status_type.ToString(); if (keys.Contains<string>("story"))
post.Story = item.story.ToString(); if (keys.Contains<string>("type"))
post.Type = item.type.ToString(); if (keys.Contains<string>("updated_time"))
post.UpdatedTime = item.updated_time.ToString(); postList.Add(post);
}
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return postList;
}

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

/// <summary>
///Get the current user info
/// </summary>
/// <author>Johnny</author>
/// <returns>return an UserInfo</returns>
/// <date>2013/10/29, 13:36:07</date>
public UserInfo GetUserInfo()
{
UserInfo userInfo = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic user = fbClient.Get("/me");
Dictionary<string, object>.KeyCollection keys = user.Keys;
userInfo = new UserInfo();
userInfo.ID = user.id.ToString();
if (keys.Contains<string>("name"))
userInfo.Name = user.name.ToString();
if (keys.Contains<string>("first_name"))
userInfo.FirstName = user.first_name.ToString();
if (keys.Contains<string>("last_name"))
userInfo.LastName = user.last_name.ToString();
if (keys.Contains<string>("username"))
userInfo.UserName = user.username.ToString();
if (keys.Contains<string>("link"))
userInfo.Link = user.link.ToString();
if (keys.Contains<string>("timezone"))
userInfo.TimeZone = user.timezone.ToString();
if (keys.Contains<string>("updated_time"))
userInfo.UpdatedTime = Convert.ToDateTime(user.updated_time);
if (keys.Contains<string>("verified"))
userInfo.Verified = user.verified.ToString();
if (keys.Contains<string>("gender"))
userInfo.Gender = user.gender.ToString();
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return userInfo;
} /// <summary>
///get friends info
/// </summary>
/// <author>Johnny</author>
/// <returns>return list of UserInfo</returns>
/// <date>2013/10/31, 15:57:40</date>
public List<UserInfo> GetFriendInfoList()
{
List<UserInfo> userList = null;
try
{
if (!string.IsNullOrEmpty(accessToken))
{
FacebookClient fbClient = new FacebookClient(accessToken);
dynamic friends = fbClient.Get("/me/friends");
if (friends != null)
{
userList = new List<UserInfo>();
foreach (dynamic item in friends.data)
{
UserInfo user = new UserInfo();
user.ID = item.id.ToString();
user.Name = item.name.ToString(); userList.Add(user);
}
}
}
else
errorMessage = ErrorTokenMessage;
}
catch (FacebookApiException fbex)
{
errorMessage = fbex.Message;
}
return userList;
}

以上就是一些常用的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. 一个IIS网站的异常配置的安全解决方案

    一个.如下面的错误: "/"应用server错. 安全异常 说明: 应用程序试图运行安全策略不同意的操作.要授予此应用程序所需的权限.请与系统管理员联系,或在配置文件里更改该应用程 ...

  2. unity脚本运行顺序具体的解释

    unity脚本自带函数执行顺序例如以下:将以下脚本挂在随意物体执行就可以得到 Awake ->OnEable-> Start ->-> FixedUpdate-> Upd ...

  3. JS如何判断包括IE11在内的IE浏览器

    原文:JS如何判断包括IE11在内的IE浏览器 今天碰到一个奇怪的问题,有一个页面,想指定用IE浏览器打开,在VS开发环境没有问题,但部署到服务器上,即使是用IE打开页面,还是提示"仅支持I ...

  4. python_基础学习_03_正则替换文本(re.sub)

    python的正则表达式模块是re,替换相关的方法是sub. 例如我们要做如下的替换将所有的 替换为空格,可以通过下面代码实现: import re input = 'hello world' #第一 ...

  5. Openstack &amp; Hadoop结合项目Sahara

    Openstack 项目Sahara,主要是用来搭建Hadoop集群,利用虚拟出来的计算资源,高速搭建Hadoop集群. Sahara项目与OPenstack其它项目的关系: 图片转自:http:// ...

  6. POJ1135_Domino Effect(最短)

    Domino Effect Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8224   Accepted: 2068 Des ...

  7. WinForms C#:html编辑器工程源码,含直接写WebBrowser的文件流、IPersistStreamInit接口的声明和一些相关的小方法

    原文:WinForms C#:html编辑器工程源码,含直接写WebBrowser的文件流.IPersistStreamInit接口的声明和一些相关的小方法 首先多谢朋友们的捧场: 今天给大家带来一个 ...

  8. C++中public,protected,private访问

    对于公有继承方式: (1)父类的public成员成为子类的public成员,允许类以外的代码访问这些成员:(2)父类的private成员仍旧是父类的private成员,子类成员不可以访问这些成员:(3 ...

  9. WPF中嵌入WinForm中的webbrowser控件

    原文:WPF中嵌入WinForm中的webbrowser控件 使用VS2008创建WPF应用程序,需使用webbrowser.从工具箱中添加WPF组件中的webbrowser发现其中有很多属性事件不能 ...

  10. Android KitCat 4.4.2 ADB 官方所支持的所有Services格式翻译

    在之前的文章中有转帖网上同行制作的ADB协议表格<<adb概览及协议参考>>,但不够详尽,所以这里自己另外基于Android 4.4.2的技术文档重新做一次翻译. HOST S ...