Facebook C#SDK,获取用户电子邮件的问题 [英] Facebook C# SDK, problems getting user email

查看:424
本文介绍了Facebook C#SDK,获取用户电子邮件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Facebook C#SDK,并获得了如何设置登录信息并获取一些用户信息以注册我的网站的示例。然而,我坚持电子邮件信息。它总是空的。



我已经检查了一些相关的帖子在这里,但没有解决我的问题。所有我需要的信息都是正确的,只有电子邮件和生日缺失。



我的代码在shtml部分页面是这样的:

 < div id =fb-root>< / div> 
< fb:login-button id =fbloginonlogin =window.open('http://'+ location.host +'/ Facebook / LogOn','_self')perms = '>< / fb:login-button>
< script>
window.fbAsyncInit = function(){
FB.init({
appId:'@ Facebook.FacebookApplication.Current.AppId',
cookie:true,
xfbml:true,
oauth:true
});

function facebooklogin(){
FB.login(function(response){
if(response.authResponse){
//用户授权的
/ /window.location.reload();
window.open(http://+ location.host +/ Facebook / LogOn,_self)
} else {
// user cancelled
}
},{scope:'@ ViewBag.ExtendedPermissions'});
};

$(function(){
//只有在加载了facebook js sdk之后才启用该按钮
$('#fblogin')。attr disabled',false).click(facebooklogin);
});
};
(function(){
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +'// connect。 facebook.net/en_US/all.js';
document.getElementById('fb-root')。appendChild(e);
}());
< / script>

我在Facebook控制器中的代码:

  public ActionResult LogOn()
{
var fbWebContext = new FacebookWebContext(); //或FacebookWebContext.Current;

if(fbWebContext.IsAuthorized())
{
var fb = new FacebookWebClient();
dynamic me = fb.Get(me);

//使用Facebook凭据创建新用户
var id = 0;
var nickname = me.first_name;
var password =;
var email = me.email;
var picture = string.Format(http://graph.facebok.com/{0}/picture?type=large,me.id);
var thumbnail = string.Format(http://graph.facebok.com/{0}/picture?type=normal,me.id);
var fullName = me.name;
var gender =;
if(me.gender ==male)gender =Masculino;
if(me.gender ==female)gender =Feminino;
var birthdate = Convert.ToDateTime(me.birthday);

//用户是否已经存在?
if(DAUser.UserAlreadyExists(email))
{
ViewBag.Message =O seu e-mailjáfoi cadastrado em nosso site。Por favor,cadastre outro e-mail。
return View(〜/ Views / Shared / Erro.cshtml);
}
else
{
id = DAUser.Create(昵称,电子邮件,密码,facebook);
}

//更新创建的用户信息
用户user = db.User.Find(id);
TryUpdateModel(user);
user.Picture = picture;
user.Thumbnail = thumbnail;
user.Nickname = nickname;
user.FullName = fullName;
user.Gender = gender;
if(!String.IsNullOrEmpty(birthdate))
{
user.Birthdate = Convert.ToDateTime(birthdate);
}

db.SaveChanges();
Session [loginType] =Facebook;

return RedirectToAction(Mural,Home);
}
else
{
ViewBag.Message =Nãofoipossívelcompletar o seu login via Facebook。
return View(〜/ Views / Shared / Erro.cshtml);
}
}

如果我把这些行, :

  [FacebookAuthorize(Permissions = ExtendedPermissions)] 

if(fbWebContext.IsAuthorized(ExtendedPermissions.Split (','))

我的应用程式停止运作。



任何人都有解决方案?



>问题是这一行:

 },{scope:'@ ViewBag.ExtendedPermissions'}); 

在我的应用程序应该是:

 },{scope:'email,user_birthday,user_hometown'}); // alter获取访问用户数据的权限

我没有设置范围



我的文化日期时间是dd / MM / yyyy,Facebook生日设置为MM / dd / yyyy,我试过这个:

  var birthdate = DateTime.Parse(me.birthday,CultureInfo.CreateSpecificCulture(pt-BR)) ; 

Cuz我在巴西的文化,但我仍然得到DateTime错误:

 字符串未被识别为有效的DateTime。 

任何人都知道如何解决这个问题?

解决方案

这一行使得一切正常的Facebook生日

  var birthdate = DateTime.ParseExact (me.birthday,MM / dd / yyyy,CultureInfo.InvariantCulture); 


I'm using Facebook C# SDK and got a sample on how to set up a login and get some user information to register im my website. However, I stuck in email information. It's always null.

I've checked some posts related in here, but none solve my problem. All the information I need is coming right, only email and birthday is missing.

My code in shtml partial page is like this:

<div id="fb-root"></div>
<fb:login-button id="fblogin" onlogin="window.open('http://' + location.host + '/Facebook/LogOn', '_self')" perms='email'></fb:login-button>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: '@Facebook.FacebookApplication.Current.AppId',
            cookie: true,
            xfbml: true,
            oauth: true
        });

        function facebooklogin() {
            FB.login(function (response) {
                if (response.authResponse) {
                    // user authorized
                    //window.location.reload();
                    window.open("http://" + location.host + "/Facebook/LogOn", "_self")
                } else {
                    // user cancelled
                }
            }, { scope: '@ViewBag.ExtendedPermissions' });
        };

        $(function () {
            // make the button is only enabled after the facebook js sdk has been loaded.
            $('#fblogin').attr('disabled', false).click(facebooklogin);
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());
</script>

And my code in Facebook Controller:

public ActionResult LogOn()
{
    var fbWebContext = new FacebookWebContext(); // or FacebookWebContext.Current;

    if (fbWebContext.IsAuthorized())
    {
        var fb = new FacebookWebClient();
        dynamic me = fb.Get("me");

        //Creating new User with Facebook credentials
        var id = 0;
        var nickname = me.first_name;
        var password = "";
        var email = me.email;
        var picture = string.Format("http://graph.facebok.com/{0}/picture?type=large", me.id);
        var thumbnail = string.Format("http://graph.facebok.com/{0}/picture?type=normal", me.id);
        var fullName = me.name;
        var gender = "";
        if (me.gender == "male") gender = "Masculino";
        if (me.gender == "female") gender = "Feminino";
        var birthdate = Convert.ToDateTime(me.birthday);

        //Does the user already exist?
        if (DAUser.UserAlreadyExists(email))
        {
            ViewBag.Message = "O seu e-mail já foi cadastrado em nosso site. Por favor, cadastre outro e-mail.";
            return View("~/Views/Shared/Erro.cshtml");
        }
        else
        {
            id = DAUser.Create(nickname, email, password, "facebook");
        }

        //Updating created user information
        User user = db.User.Find(id);
        TryUpdateModel(user);
        user.Picture = picture;
        user.Thumbnail = thumbnail;
        user.Nickname = nickname;
        user.FullName = fullName;
        user.Gender = gender;
        if (!String.IsNullOrEmpty(birthdate))
        {
            user.Birthdate = Convert.ToDateTime(birthdate);
        }

        db.SaveChanges();
        Session["loginType"] = "Facebook";

        return RedirectToAction("Mural", "Home");
    }
    else
    {
        ViewBag.Message = "Não foi possível completar o seu login via Facebook.";
        return View("~/Views/Shared/Erro.cshtml");
    }
}

If I put these lines, as shown in the sample:

[FacebookAuthorize(Permissions = ExtendedPermissions)]

if (fbWebContext.IsAuthorized(ExtendedPermissions.Split(',')))

My app stop works.

Anybody has a solution? O another sample codes to get authorized to request email and birthday?

Edit

The problem was this line:

}, { scope: '@ViewBag.ExtendedPermissions' });

In my App should be:

}, { scope: 'email,user_birthday,user_hometown' }); //alter to get permission to access user data

I didn't set a scope (perms) to facebook access... but now, I have another question.

My culture DateTime is dd/MM/yyyy and Facebook birthday is set up as MM/dd/yyyy, I tried this:

var birthdate = DateTime.Parse(me.birthday, CultureInfo.CreateSpecificCulture("pt-BR"));

Cuz my culture in Brazilian, but I still get DateTime error:

String was not recognized as a valid DateTime.

Anyone know how to solve that?

解决方案

This line make everything works fine with Facebook Birthday

var birthdate = DateTime.ParseExact(me.birthday, "MM/dd/yyyy", CultureInfo.InvariantCulture);

这篇关于Facebook C#SDK,获取用户电子邮件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆