2016-05-27 42 views
1

我正在開發一個ASP.NET MVC應用程序。在我的應用程序中,我需要爲用戶提供Faccebook登錄服務。此外,我需要從Facebook中檢索用戶電子郵件並存儲在數據庫中。從Facebook獲取電子郵件在ASP.NET MVC中投入null例外

我正在使用Visual Studio 2013和ASP.NET MVC5。我的Facebook登錄方法工作正常。但是當我從Facebook取回電子郵件時,它給了我一個空例外。我的externalLoginCallback方法如下:

[AllowAnonymous] 
     public async Task<ActionResult> ExternalLoginCallback(string returnUrl) 
     { 

var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie); 
      if (result == null || result.Identity == null) 
      { 
       return RedirectToAction("Login"); 
      } 

      var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier); 
      if (idClaim == null) 
      { 
       return RedirectToAction("Login"); 
      } 

      var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value); 

      var name = result.Identity.Name == null ? "" : result.Identity.Name.Replace(" ", ""); 

      //retrieving email from facebook here 
      var externalIdentity = HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie); 
      var emailClaim = externalIdentity.Result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email); 
      var email = emailClaim.Value;//this line is throwing null exception 


. 
. 
. 
} 

我評論了錯誤在我的代碼中拋出的位置。

這是我如何Startup.Auth.cs

var facebookAuthenticationOptions = new FacebookAuthenticationOptions() 
{ 
    AppId = "x", 
    AppSecret = "y" 
}; 
facebookAuthenticationOptions.Scope.Add("email"); 
app.UseFacebookAuthentication(facebookAuthenticationOptions); 

我也試過這樣配置的Facebook:

app.UseFacebookAuthentication(new FacebookAuthenticationOptions 
      { 
       AppId = "x", 
       AppSecret = "y", 
       Scope = { "email" }, 
       Provider = new FacebookAuthenticationProvider 
       { 
        OnAuthenticated = context => 
        { 
         context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); 
         return Task.FromResult(true); 
        } 
       } 
      }); 

兩者都不能正常工作。我的代碼出了什麼問題,我該如何解決它?

回答

0

你可以試試這個:

var facebookAuthenticationOptions = new FacebookAuthenticationOptions() 
    { 
     AppId = "xxxxxxx", 
     AppSecret = "xxxxxx", 
     BackchannelHttpHandler = new FacebookBackChannelHandler(), 
     UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location" 
    }; 

,然後定義這個類:

public class FacebookBackChannelHandler : HttpClientHandler 
{ 
    protected override async System.Threading.Tasks.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")); 
     } 

     var response = await base.SendAsync(request, cancellationToken); 
     return response; 
    } 
} 

最後,您可以通過在「ExternalLoginCallback以下獲取電子郵件(和名字,姓氏,位置) 「帳戶控制器中的方法:

[AllowAnonymous] 
     public async Task<ActionResult> ExternalLoginCallback(string returnUrl) 
     { 
      var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 
      if (loginInfo == null) 
      { 
       return RedirectToAction("LoginRegister"); 
      } 

      // GET MAIL AND NAME 
      var email = loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email).Value; 
      var name= loginInfo.ExternalIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value; 
+0

什麼命名空間我需要有我無法找到loginInfo.ExternalIdentit y – Kasparov92

+0

var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 此代碼適用於具有Identity的ASP.Net MVC應用程序。 AuthenticationManager是Owin的一部分:(HttpContext.GetOwinContext()。Authentication) – Gonzalo

相關問題