我正在尝试从Facebook获取用户名和用户电子邮件.我阅读了很多关于这个主题的信息,这是我的最终代码,仅在我的facebook app管理员帐户上有效:
public partial class Startup { public void ConfigureAuth(IAppBuilder app) { /*Other external login options*/ var FacebookOptions = new FacebookAuthenticationOptions() { AppId = "My App Id",AppSecret = "My App Secret",SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,BackchannelHttpHandler = new FacebookBackChannelHandler(),UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email" }; } } public class FacebookBackChannelHandler : HttpClientHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) { if (!request.RequestUri.AbsolutePath.Contains("/oauth")) { request.RequestUri = new Uri(request.RequestUri.AbsoluteUri.Replace("?access_token","&access_token")); } return await base.SendAsync(request,cancellationToken); } } public class AccountController : Controller { public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); /*my sign in code that works on my facebook app admin account*/ } }
在每个帐号我得到loginInfo.Email等于null.
当有人点击“使用Facebook登录”时,他会收到以下消息:
如果我点击“查看您提供的信息”,我会得到:
我错过了什么?为什么不起作用?
解决方法
终于找到了答案!所有需要做的就是将Scope = {“email”}添加到FacebookOptions,这就解决了这个问题!
我的代码现在:
public partial class Startup { public void ConfigureAuth(IAppBuilder app) { /*Other external login options*/ var FacebookOptions = new FacebookAuthenticationOptions() { AppId = "My App Id",Scope = { "email" },email" }; } }
其余代码保持不变.如果此问题返回,我只为案例添加了错误页面:
public class AccountController : Controller { public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if(loginInfo.Email == null) { return RedirectToAction("FacebookError","Account"); } /*my sign in code*/ } }