使用asp.net发表评论到Facebook墙

时间:2011-04-08 15:42:55

标签: asp.net facebook facebook-graph-api

我有一个网站,我已注册为Facebook应用程序 - 我现在有一个应用程序ID。

我的网站是ASP.net C#。当用户点击按钮时,我希望它将预定义的消息发布到他们的墙上。我期待Facebook向用户提供登录对话框 - 他们登录并为我的网站应用授予发布权限。

有没有人有任何示例代码可以执行此操作?我想我需要使用图形API,但我见过的所有示例都使用PHP - 我对此一无所知。我正在寻找一个使用Java Script(我几乎什么都不知道)或C#(漂亮!)的例子。

*更新*

我设法获得了access_token。现在我通过Facebook C#API拨打电话发布到墙上。我收到错误消息:

(#803)您请求的部分别名不存在:profile_id

我已经通过api代码,发现它正试图发布到以下地址:{ https://graph.facebook.com/PROFILE_ID/feed },帖子数据是:message = Sample + message + from + c%23 + sdk& access_token = 199209316768200 | 2.1avFTZuDGR4HJ7jPFeaO3Q __。3600.1302897600.1-100000242760733 | R4DkNDf4JCb6B2F64n5TSQwBqvM

我很确定我的令牌应该有效。在请求访问令牌之前,我在应用程序授权请求中请求了publish_stream,如下所示:

Response.Redirect ("https://www.facebook.com/dialog/oauth?client_id=" + myAppId + "&redirect_uri=" + myURL + "&scope=publish_stream");

实际发出请求的sdk代码如下:

private string MakeRequest(Uri url, HttpVerb httpVerb,
                                   Dictionary<string, string> args)
        { 
        if (args != null && args.Keys.Count > 0 && httpVerb == HttpVerb.GET)
        {
            url = new Uri(url.ToString() + EncodeDictionary(args, true));
        }

        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

        request.Method = httpVerb.ToString();

        if (httpVerb == HttpVerb.POST)
        {
            string postData = EncodeDictionary(args, false);

            ASCIIEncoding encoding = new ASCIIEncoding();
            byte[] postDataBytes = encoding.GetBytes(postData);

            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataBytes.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postDataBytes, 0, postDataBytes.Length);
            requestStream.Close();
        }

        try
        {
            using (HttpWebResponse response 
                    = request.GetResponse() as HttpWebResponse)
            {
                StreamReader reader 
                    = new StreamReader(response.GetResponseStream());

                return reader.ReadToEnd();
            }
        }

谁能看到我做错了什么?

非常感谢,

罗布。

5 个答案:

答案 0 :(得分:2)

首先,您需要照顾Authentication。您需要创建一个应用程序,并使用OAuth来获取访问令牌。这些都在身份验证指南中进行了描述。

要将内容发布到用户的墙上,请查看发布下的Graph API

首先,您可以使用Facebook's C# SDK

答案 1 :(得分:1)

您可以使用像http://facebooknet.codeplex.com/这样的.NET库来执行此操作。那里有一对,我只记得这一个......

HTH。

答案 2 :(得分:1)

我创建了一个视频,展示了如何使用OG执行此操作:http://www.markhagan.me/Samples/Grant-Access-And-Post-As-Facebook-User-ASPNet

如果您没有时间观看视频,请输入完整代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Facebook;

namespace FBO
{
    public partial class facebooksync : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            CheckAuthorization();
        }

        private void CheckAuthorization()
        {
            string app_id = "374961455917802";
            string app_secret = "9153b340ee604f7917fd57c7ab08b3fa";
            string scope = "publish_stream,manage_pages";

            if (Request["code"] == null)
            {
                Response.Redirect(string.Format(
                    "https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
                    app_id, Request.Url.AbsoluteUri, scope));
            }
            else
            {
                Dictionary<string, string> tokens = new Dictionary<string, string>();

                string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
                    app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);

                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    string vals = reader.ReadToEnd();

                    foreach (string token in vals.Split('&'))
                    {
                        //meh.aspx?token1=steve&token2=jake&...
                        tokens.Add(token.Substring(0, token.IndexOf("=")),
                            token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
                    }
                }

                string access_token = tokens["access_token"];

                var client = new FacebookClient(access_token);

                client.Post("/me/feed", new { message = "markhagan.me video tutorial" });
            }
        }
    }
}

答案 3 :(得分:0)

我正在使用此http://facebooksdk.codeplex.com/。我正在使用最新的稳定版本,易于使用。要发表评论,只需发布​​/ OBJECT_ID /条评息,请参阅http://developers.facebook.com/docs/reference/api/#publishinghttp://developers.facebook.com/docs/reference/api/post/

答案 4 :(得分:0)

我最近开发的这个API如何更轻松地与Facebook集成。

以下是您的代码示例,该网站上有更多文档。

验证用户

Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[application_id]","applicaiton_secret")
'Redirects user to facebooks
SI.AuthenticateUser("http://[my url]", New SessionInfo.PermissionsEnum(){SessionInfo.PermissionsEnum.email, SessionInfo.PermissionsEnum.read_stream}))
'Called when the user is returned to your page
Dim FSR = FS.ReadFacebooAuthResponse
Response.Write(FSR.Access_Token)
Response.Write(FSR.UserID)

制作帖子

Imports Branches.FBAPI
...
Dim SI As New SessionInfo("[access_token]"))
Dim Posts = New Functions.Posts(SI)
Dim P As New Post
P.name = "name of post"
P.message = "message"
P.link = "www.cnn.com"
P.caption = "my caption"
Posts.PublishCreate("[object ID to post to]", P)
Dim PostID = P.id

从图表中获取内容。

Dim SI As New SessionInfo("[access_token]"))
Dim Req New Functions.Requests(SI)
Dim User = Req.GetUserInfo("[optional user ID]")
Response.Write(U.name)