(无法)开始使用Facebook C#SDK

时间:2012-07-11 13:53:01

标签: c# asp.net-mvc facebook-c#-sdk

我的目标是使用FB登录按钮,以便FB用户可以登录我的ASP.NET MVC 3网站。最近Facebook C#SDK的情况似乎发生了变化,所有old examples都不适用于新版本。我已经尝试了一天让他们上班......我正在处理教程Getting Started with the Facebook C# SDK for ASP.NET

目前,当我浏览http://localhost:8033/时,它似乎会自动登录(即使重新启动Chrome后),因为它显示" my-name 使用我的应用内名称"并显示我的照片。我希望它显示一个FB登录按钮。当我转到http://localhost:8033/Home/About时,我收到Session["AccessToken"]为空的错误(这是有道理的,因为它显然没有设置)。

以下是我所拥有的:

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;

namespace FacebookTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            var accessToken = Session["AccessToken"].ToString();
            var client = new FacebookClient(accessToken);
            dynamic result = client.Get("me", new { fields = "name,id" });
            string name = result.name;
            string id = result.id;

            ViewBag.Message = "Hello id: " + id;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult FacebookLogin(HttpContext context)
        {
            var accessToken = context.Request["accessToken"];
            context.Session["AccessToken"] = accessToken;

            return RedirectToAction("About");
        }
    }
}

Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            //appId: 'YOUR_APP_ID', // App ID
            appId: '<MY-NUMBER-REMOVED>', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        // Additional initialization code here
        FB.Event.subscribe('auth.authResponseChange', function (response) {
            if (response.status === 'connected') {
                // the user is logged in and has authenticated your
                // app, and response.authResponse supplies
                // the user's ID, a valid access token, a signed
                // request, and the time the access token 
                // and signed request each expire
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;

                // TODO: Handle the access token
                // Do a post to the server to finish the logon
                // This is a form post since we don't want to use AJAX
                var form = document.createElement("form");
                form.setAttribute("method", 'post');
                //form.setAttribute("action", '/FacebookLogin.ashx');
                form.setAttribute("action", '/Home/FacebookLogin');

                var field = document.createElement("input");
                field.setAttribute("type", "hidden");
                field.setAttribute("name", 'accessToken');
                field.setAttribute("value", accessToken);
                form.appendChild(field);

                document.body.appendChild(form);
                form.submit();

            } else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook, 
                // but has not authenticated your app
            } else {
                // the user isn't logged in to Facebook.
            }
        });
    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));
</script>

<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1"></div>

About.cshtml

@{
    ViewBag.Title = "About Us";
}

<h2>About</h2>
<p>
     @ViewBag.Message
</p>

你能告诉我如何解决这个问题,以便显示一个FB登录按钮,点击它时会要求用户进行FB身份验证,发送回来,然后我的应用会将他们识别为登录用户吗? / p>

1 个答案:

答案 0 :(得分:3)

对于“登录”按钮,如果您在访问应用程序之前登录到Facebook,则会看到面部而不是登录按钮,获取“登录”按钮的唯一方法是转到facebook.com并注销或使用C#SDK进行facebook注销。根据您的要求,这可能是也可能不是您想要的。如果这是您真正想要的,那么SDK文档中会有一些Re-Authentication

我通过删除submit()来调整你的应用程序,并用ajax帖子替换它,FacebookLogin操作被更改了,我在About操作上添加了一些错误处理。您的原始应用程序将起作用,但如果您已登录Facebook,它将自动重定向到“关于”。

更新添加了一个不使用Javascript的登录链接,插入appid和appsecret并相应地调整portnumber。这是根据找到的here服务器端登录样本改编的,它比这段代码更漂亮:)

注意在服务器端流中传递的状态值应该是您应该在ConnectResponse()方法中验证的unqiue值,即在FacebookLoginNoJs中生成一个值并确保它在ConnectResponse可防止跨网站请求forgery

<强> HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Facebook;

namespace FacebookTest.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Please log in first";

            if (Session["AccessToken"] != null)
            {
                var accessToken = Session["AccessToken"].ToString();
                var client = new FacebookClient(accessToken);

                try
                {
                    dynamic result = client.Get("me", new { fields = "name,id" });
                    string name = result.name;
                    string id = result.id;

                    ViewBag.Message = "Hello id: " + id + " aka " + name;
                }
                catch (FacebookOAuthException x)
                {

                }
            }

            return View();
        }

        public void FacebookLogin(string uid, string accessToken)
        {
            var context = this.HttpContext;
            context.Session["AccessToken"] = accessToken;
        }

        public ActionResult FacebookLoginNoJs()
        {
            return Redirect("https://www.facebook.com/dialog/oauth?client_id=MY-APPID-REMOVED&redirect_uri=http://localhost:45400/Home/ConnectResponse&state=secret");
        }

        public ActionResult ConnectResponse(string state, string code, string error, string error_reason, string error_description, string access_token, string expires)
        {
            if (string.IsNullOrEmpty(error))
            {
                try
                {
                    var client = new FacebookClient();
                    dynamic result = client.Post("oauth/access_token",
                                              new
                                              {
                                                  client_id = "MY-APPID-REMOVED",
                                                  client_secret = "MY-APP-SECRET-REMOVED",
                                                  redirect_uri = "http://localhost:45400/Home/ConnectResponse",
                                                  code = code
                                              });

                    Session["AccessToken"] = result.access_token;

                    if (result.ContainsKey("expires"))
                        Session["ExpiresIn"] = DateTime.Now.AddSeconds(result.expires);

                }
                catch
                {
                    // handle errors
                }
            }
            else
            {
               // Declined, check error
            }

            return RedirectToAction("Index");
        }

    }
}

<强> Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<h2>@ViewBag.Message</h2>
<p>
    To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
</p>

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            //appId: 'YOUR_APP_ID', // App ID
            appId: 'MY-APPID-REMOVED', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });

        // Additional initialization code here
        FB.Event.subscribe('auth.authResponseChange', function (response) {
            if (response.status === 'connected') {

                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;

                var url = '/Home/FacebookLogin';
                $.post(url, { uid: uid, accessToken: accessToken }, function (data) {
                });

            } else if (response.status === 'not_authorized') {
                // the user is logged in to Facebook, 
                // but has not authenticated your app
            } else {
                // the user isn't logged in to Facebook.
            }
        });
    };

    // Load the SDK Asynchronously
    (function (d) {
        var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
        if (d.getElementById(id)) { return; }
        js = d.createElement('script'); js.id = id; js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        ref.parentNode.insertBefore(js, ref);
    } (document));
</script>

<div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1"></div>

@Html.ActionLink("The NoJs Login", "FacebookLoginNoJs", "Home")

<强> About.cshtml

@{
    ViewBag.Title = "About Us";
}

<h2>About</h2>
<p>
        @ViewBag.Message
</p>