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

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

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

  这些信息都是要用到的。

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

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

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

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

5、一切准备就绪,现在开始使用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("登录失败!");
}

6、登入成功之后会跳转到上文提到的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();
}

7、拿到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;
}

希望这些也能让需要的人看到,对大家有所帮助。

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

  1. 浅谈Facebook的服务器架构(组图)

    导读:毫无疑问,作为全球最领先的社交网络,Facebook的高性能集群系统承担了海量数据的处理,它的服务器架构一直为业界众人所关注.CSDN博主yanghehong在他自己最新的一篇博客< Fa ...

  2. 浅谈Facebook的服务器架构

    导读:毫无疑问,作为全球最领先的社交网络,Facebook的高性能集群系统承担了海量数据的处理,它的服务器架构一直为业界众人所关注.CSDN博主yanghehong在他自己最新的一篇博客< Fa ...

  3. 浅谈API和SDK的区别

    首先了解一下他们的定义 API:application program interface 应用程序接口 通常表示一些事先定义好的函数,为了向外部提供一组功能的实现,实现和其他软件的交互 SDK:so ...

  4. facebook .net sdk 应用

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

  5. 【转】Windows SDK入门浅谈

    前言 如果你是一个编程初学者,如果你刚刚结束C语言的课程.你可能会有点失望和怀疑:这就是C语言吗?靠它就能编出软件?无法想象Windows桌面上一个普通的窗口是怎样出现在眼前的.从C语言的上机作业到W ...

  6. Android应用安全开发之浅谈加密算法的坑

      <Android应用安全开发之浅谈加密算法的坑> 作者:阿里移动安全@伊樵,@舟海 阿里聚安全,一站式解决应用开发安全问题     Android开发中,难免会遇到需要加解密一些数据内 ...

  7. [nRF51822] 14、浅谈蓝牙低功耗(BLE)的几种常见的应用场景及架构(科普类干货)

    蓝牙在短距离无线通信领域占据举足轻重的地位—— 从手机.平板.PC到车载设备, 到耳机.游戏手柄.音响.电视, 再到手环.电子秤.智能医疗器械(血糖仪.数字血压计.血气计.数字脉搏/心率监视器.数字体 ...

  8. 【转载】浅谈游戏开发之2D手游工具

    浅谈游戏开发之2D手游工具 来源:http://www.gameres.com/459713.html 游戏程序 平台类型: iOS Android  程序设计: 其它  编程语言:   引擎/SDK ...

  9. Android性能优化的浅谈

    一.概要: 本文主要以Android的渲染机制.UI优化.多线程的处理.缓存处理.电量优化以及代码规范等几方面来简述Android的性能优化 二.渲染机制的优化: 大多数用户感知到的卡顿等性能问题的最 ...

随机推荐

  1. https采集12306(复制)

    package train; import java.io.IOException;import java.security.NoSuchAlgorithmException;import java. ...

  2. 浅谈rem、em、px

    1.px:像素(Pixel) px是相对长度单位,他是相对于显示器屏幕分辨率而言的 优点:比较稳定.精确 缺点:在浏览器 中放大或者缩小浏览页面,会出现页面混乱的情况. 如下例子: .buttonPX ...

  3. odoo 10 生产自动领料

    分析源码 当 原材料的 补货规则 的 "补货位置" location_id 是 生产单 的 原材料 "目标位置 ", 并且 原材料的 补货规则 的 " ...

  4. js原生ajax请求get post笔记

    开拓新领域,贵在记录.下面记录了使用ajax请求的get.post示例代码 //ajax get 请求获取数据支持同步异步 var ajaxGet = function (reqUrl, params ...

  5. [翻译][erlang]cowboy handler模块的使用

    关于Cowboy Cowboy是基于Erlang实现的一个轻量级.快速.模块化的http web服务器. Handlers,用于处理HTTP请求的程序处理模块. Plain HTTP Handlers ...

  6. IIS配置excel 权限

    http://www.cnblogs.com/zhuxiaohui/archive/2013/10/16/3371637.html

  7. vuex2.0.0爬坑记录 -- mutations的第一个参数state不能解构

    今天在学习vuex的过程中,遇到了一个很困扰人的问题,最终利用vuex的状态快照工具logger解决了问题. 问题是这样的,我在子组件中使用了mapState()函数来将状态映射至子组件中,使子组件能 ...

  8. 【IOS】Xcode7以上免证书真机调试

    Xcode7之前,想要真机调试,必须花99刀购买开发者账号,而且步骤繁琐,需要下载证书.随着Xcode7的推出,大幅度的简化了真机调试的步骤,对ios开发工作者和正在学习ios开发的众多码农们,可以说 ...

  9. 在 iTunes content中创建新的版本时,出现构建版本后面没有加号。

    老项目升级时,提交版本时,ipa已经上传成功到APP store,但是构建版本后面一直都没有加号,等了一夜还是没有反应 后来苹果发来一封邮件,意思是,我需要在plist文件中添加一个NSMicroph ...

  10. myeclipse中UTF-8设置

      myeclipse中UTF-8设置 如果要使插件开发应用能有更好的国际化支持,能够最大程度的支持中文输出,则最好使 Java文件使用UTF-8编码.然而,Eclipse工作空间(workspace ...