C# 使用OWIN在ASP.NET MVC 5应用程序中存储和检索facebook访问令牌

C# 使用OWIN在ASP.NET MVC 5应用程序中存储和检索facebook访问令牌,c#,asp.net,facebook,asp.net-mvc-5,owin,C#,Asp.net,Facebook,Asp.net Mvc 5,Owin,我是奥文的新手。目前我正在使用visual studio 2015创建ASP.NET MVC项目,visual studio向导可以处理几乎所有的基本功能,如注册新用户、使用外部帐户登录。。。 在Startup.Auth.cs中,我实现了使用facebook登录的功能,如下所示: var option = new FacebookAuthenticationOptions { AppId = appId, AppSecret = a

我是奥文的新手。目前我正在使用visual studio 2015创建ASP.NET MVC项目,visual studio向导可以处理几乎所有的基本功能,如注册新用户、使用外部帐户登录。。。 在Startup.Auth.cs中,我实现了使用facebook登录的功能,如下所示:

var option = new FacebookAuthenticationOptions
        {
            AppId = appId,
            AppSecret = appSecret,
            Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = (ctx) =>
                {
                    ctx.Identity.AddClaim(new System.Security.Claims.Claim("fb_access_token", ctx.AccessToken, ClaimValueTypes.String, "Facebook"));
                    return Task.FromResult(0);
                }
            },
            AuthenticationType = DefaultAuthenticationTypes.ExternalCookie
        };
        app.UseFacebookAuthentication(option);
在AccountController.cs中,我希望获取访问令牌以获取某些用户的信息,但我始终收到索赔对象的空引用异常:

public ActionResult Test()
{
    ClaimsIdentity claimIdenties = HttpContext.User.Identity as ClaimsIdentity;
    var claim = claimIdenties.FindFirst("fb_access_token");
    return View(claim.Value);
}
你们能给我一些建议吗


很抱歉,我在注册facebook时英语不好。让我们将access token存储在我们的数据库中,以便稍后检索。因此,在您的帐户控制器中

  var claimsIdentity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
            if (claimsIdentity != null)
            {
                // Retrieve the existing claims for the user and add the FacebookAccessTokenClaim
                var currentClaims = await UserManager.GetClaimsAsync(user.Id);
                var facebookAccessToken = claimsIdentity.FindAll("FacebookAccessToken").First();
                if (currentClaims.Count() <= 0)
                {
                    await UserManager.AddClaimAsync(user.Id, facebookAccessToken);
                }
这对我非常有效

 var fb = new FacebookClient(loginInfo.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value);
                    dynamic userfbData = fb.Get("/me?fields=email,name");
                    picurl = String.Format("https://graph.facebook.com/{0}/picture?type=large", userfbData.id);
                    dispname = userfbData.name;