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);
}
}
});
兩者都不能正常工作。我的代碼出了什麼問題,我該如何解決它?
什麼命名空間我需要有我無法找到loginInfo.ExternalIdentit y – Kasparov92
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); 此代碼適用於具有Identity的ASP.Net MVC應用程序。 AuthenticationManager是Owin的一部分:(HttpContext.GetOwinContext()。Authentication) – Gonzalo