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

标签 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 重新启动后),因为它显示“我的名称使用我的应用程序名称”并显示我的图片。我希望它会显示 FB 登录按钮。当我去 http://localhost:8033/Home/About我收到错误 Session["AccessToken"]为 null(这是有道理的,因为它显然没有被设置)。

这是我所拥有的:

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>

关于.cshtml

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

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

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

最佳答案

至于登录按钮,如果您在访问应用程序之前登录了 Facebook,您将看到面孔而不是登录按钮,恢复登录按钮的唯一方法是访问 facebook.com 并注销,或者可能使用 C# SDK 进行 facebook 注销。根据您的要求,这可能是也可能不是您想要的。有一点关于Re-Authentication如果这是您真正想要的,请在 SDK 文档中查看。

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

更新添加了一个不使用Javascript的登录链接,插入appid和appsecret并相应地调整端口号。这是根据发现的服务器端登录示例改编的 here这比这段代码漂亮得多:)

注意 在服务器端流程中传递的状态值应该是一个独特的值,您应该在 ConnectResponse() 方法中验证该值,即在 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")

关于.cshtml

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

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

关于c# - (无法)开始使用 Facebook C# SDK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434208/

相关文章:

c# - 带有消息队列的发布订阅者模型库

C# 正则表达式只允许字母数字

c# - 我怎样才能在这里提取代码重复?

asp.net-mvc - 努力解决标准 Azure 网站中的 "Cold"代码问题

angularjs - ASP.NET MVC 中的 AngularJS 是否有用于强类型化的功能?

asp.net - Facebook 标签身份验证

C# 字典到 .csv

c# - 为什么 SASS @mixin 不能在 Visual Studio 中工作?

c# - Silverlight 中的请求对话框

facebook - 如何获得对特定 Facebook 页面或应用程序的管理页面权限?