gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:27:06 25 4
gpt4 key购买 nike

我的目标是使用 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-app-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 身份验证,将他们发回,然后我的应用程序将他们识别为已登录用户吗?

最佳答案

至于登录按钮,如果您在访问您的应用程序之前登录到 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")

About.cshtml

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com