【问题标题】:How to access the users Email id with asp.net mvc facebook?如何使用 asp.net mvc facebook 访问用户的电子邮件 ID?
【发布时间】:2017-07-14 15:15:50
【问题描述】:

我使用这个Link 作为起点,因为我是 Asp.net MVC 的新手。

我已经能够获取 facebook 用户的数据我应该使用什么权限来获取用户的电子邮件 ID 以及在哪里?

dynamic me = client.Get("me");
if (response.ContainsKey("verified"))
{
    facebookVerified = response["verified"];
}
else
{
    facebookVerified = false;
}
db.ExternalUsers.Add(new ExternalUserInformation
{
     UserId = newUser.UserId,
     FullName = me.name,
     Link = me.link,
     Email = model.Email, // Want the Email ID from Facebook
     Gender = me.gender,
     Verified = facebookVerified
});

登录代码:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
    {
        return RedirectToLocal(returnUrl);
    }

    // If we got this far, something failed, redisplay form
    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return View(model);
}

【问题讨论】:

  • 这应该回答你的问题:stackoverflow.com/a/13125765/1346943
  • 您的问题解决了吗?如果是,请写下正确答案并采纳
  • 不,还没有解决
  • 请显示您使用的登录代码。
  • 已解决问题

标签: c# facebook asp.net-mvc-4 facebook-graph-api


【解决方案1】:

您在这里缺少的是获得从 facebook 获取电子邮件地址的额外权限。

请参阅下面的两个屏幕截图,第二个屏幕截图要求提供包括电子邮件在内的其他信息。

基本权限

更多权限

为此,您需要将此附加必需信息作为“范围”。

我今天做了一个关于如何使用 facebook 登录的小教程,可以在这里阅读 - Using Facebook Login with ASP.NET MVC 4。这将回答您的大部分问题。

对于您的问题,您应该这样做:

创建一个 FacebookScopedClient 类(代码如下),然后在您的 AuthConfig.cs 中像这样使用它

var facebooksocialData = new Dictionary<string, object>();
facebooksocialData.Add("scope", "email, publish_stream, read_stream");

OAuthWebSecurity.RegisterClient(new FacebookScopedClient(
    appId: "xxxxxxxx",
    appSecret: "xxxxxxxxxxxxxxxxxxx",
    scope:"email, user_likes, friends_likes, user_birthday),
    "Facebook",
    null
);

FacebookScopedClient 类的代码 -

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using DotNetOpenAuth.AspNet;
using Newtonsoft.Json;

public class FacebookScopedClient : IAuthenticationClient
{
    private string appId;
    private string appSecret;
    private string scope;

    private const string baseUrl = "https://www.facebook.com/dialog/oauth?client_id=";
    public const string graphApiToken = "https://graph.facebook.com/oauth/access_token?";
    public const string graphApiMe = "https://graph.facebook.com/me?";

    private static string GetHTML(string URL)
    {
        string connectionString = URL;

        try
        {
            System.Net.HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(connectionString);
            myRequest.Credentials = CredentialCache.DefaultCredentials;
            //// Get the response
            WebResponse webResponse = myRequest.GetResponse();
            Stream respStream = webResponse.GetResponseStream();
            ////
            StreamReader ioStream = new StreamReader(respStream);
            string pageContent = ioStream.ReadToEnd();
            //// Close streams
            ioStream.Close();
            respStream.Close();
            return pageContent;
        }
        catch (Exception)
        {
        }
        return null;
    }

    private IDictionary<string, string> GetUserData(string accessCode, string redirectURI)
    {
        string token = GetHTML(graphApiToken + "client_id=" + appId + "&redirect_uri=" + HttpUtility.UrlEncode(redirectURI) + "&client_secret=" + appSecret + "&code=" + accessCode);
        if (token == null || token == "")
        {
            return null;
        }
        string access_token = token.Substring(token.IndexOf("access_token="), token.IndexOf("&"));
        string data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);

        // this dictionary must contains
        Dictionary<string, string> userData = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);
        return userData;
    }

    public FacebookScopedClient(string appId, string appSecret, string scope)
    {
        this.appId = appId;
        this.appSecret = appSecret;
        this.scope = scope;
    }

    public string ProviderName
    {
        get { return "Facebook"; }
    }

    public void RequestAuthentication(System.Web.HttpContextBase context, Uri returnUrl)
    {
        string url = baseUrl + appId + "&redirect_uri=" + HttpUtility.UrlEncode(returnUrl.ToString()) + "&scope=" + scope;
        context.Response.Redirect(url);
    }

    public AuthenticationResult VerifyAuthentication(System.Web.HttpContextBase context)
    {
        string code = context.Request.QueryString["code"];

        string rawUrl = context.Request.Url.OriginalString;
        //From this we need to remove code portion
        rawUrl = Regex.Replace(rawUrl, "&code=[^&]*", "");

        IDictionary<string, string> userData = GetUserData(code, rawUrl);

        if (userData == null)
            return new AuthenticationResult(false, ProviderName, null, null, null);

        string id = userData["id"];
        string username = userData["username"];
        userData.Remove("id");
        userData.Remove("username");

        AuthenticationResult result = new AuthenticationResult(true, ProviderName, id, username, userData);
        return result;
    }
}

参考资料:

【讨论】:

  • 仅供参考,我遇到的问题。首先,在这一行“范围:”电子邮件,用户喜欢,朋友喜欢,用户生日)中缺少一个类型“之前)”。现在最重要的是,username 在较新的 facebook api 中已弃用,这将导致异常,因为不会返回任何数据。所以从这一行字符串中删除用户名 data = GetHTML(graphApiMe + "fields=id,name,email,username,gender,link&" + access_token);而且由于我们没有收到它,所以我更改了字符串用户名 = userData["username"];字符串用户名 = userData["name"];并删除了这一行:userData.Remove("username"); Cheers
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多