C# facebook成功登录后ExternalLoginConfirmation返回null

C# facebook成功登录后ExternalLoginConfirmation返回null,c#,facebook,asp.net-mvc-5,C#,Facebook,Asp.net Mvc 5,在MVC5模板中实现Facebook登录,添加了应用Id和密码 最初登录失败,因为它返回null public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { // Crashes on this line var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInf

在MVC5模板中实现Facebook登录,添加了应用Id和密码

最初登录失败,因为它返回null

public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    // Crashes on this line
    var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
}
public异步任务ExternalLoginCallback(string returnUrl)
{
//在这条线上撞车
var loginInfo=await AuthenticationManager.GetExternalLoginInfoAsync();
if(loginInfo==null)
{
返回重定向操作(“登录”);
}
}
在搜索之后,我发现了一个解决方案,它说用这个方法替换现有的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(" ", "");

        // Sign in the user with this external login provider if the user already has a login
        var user = await UserManager.FindAsync(login);
        if (user != null)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToLocal(returnUrl);
        }
        else
        {
            // If the user does not have an account, then prompt the user to create an account
            ViewBag.ReturnUrl = returnUrl;
            ViewBag.LoginProvider = login.LoginProvider;
            return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { UserName = name });
        }
    }
[AllowAnonymous]
公共异步任务ExternalLoginCallback(字符串返回URL)
{
var result=wait AuthenticationManager.authenticateSync(DefaultAuthenticationTypes.ExternalCookie);
if(result==null | | result.Identity==null)
{
返回重定向操作(“登录”);
}
var idClaim=result.Identity.FindFirst(ClaimTypes.NameIdentifier);
if(idClaim==null)
{
返回重定向操作(“登录”);
}
var login=new UserLoginInfo(idClaim.Issuer,idClaim.Value);
var name=result.Identity.name==null?“:result.Identity.name.Replace(“,”);
//如果用户已经登录,请使用此外部登录提供程序登录该用户
var user=await UserManager.FindAsync(登录);
如果(用户!=null)
{
等待信号同步(用户,ispersist:false);
返回重定向到本地(returnUrl);
}
其他的
{
//如果用户没有帐户,则提示用户创建帐户
ViewBag.ReturnUrl=返回URL;
ViewBag.LoginProvider=login.LoginProvider;
返回视图(“ExternalLoginConfirmation”,新的ExternalLoginConfirmationViewModel{UserName=name});
}
}
现在这个问题已经解决了,但当我尝试关联你的Facebook帐户时。 您已成功通过Facebook的身份验证。请在下面输入此网站的用户名,然后单击“注册”按钮完成登录

[HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
    {
        if (User.Identity.IsAuthenticated)
        {
            return RedirectToAction("Manage");
        }

        if (ModelState.IsValid)
        {
            // Here comes the error System.NullReferenceException: Object reference not set to an instance of an object.

            var info = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return View("ExternalLoginFailure");
            }
            var user = new ApplicationUser() { UserName = model.UserName };
            var result = await UserManager.CreateAsync(user);
            if (result.Succeeded)
            {
                result = await UserManager.AddLoginAsync(user.Id, info.Login);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToLocal(returnUrl);
                }
            }
            AddErrors(result);
        }

        ViewBag.ReturnUrl = returnUrl;
        return View(model);
    }
[HttpPost]
[异名]
[ValidateAntiForgeryToken]
公共异步任务ExternalLoginConfirmation(ExternalLoginConfirmationViewModel模型,字符串返回URL)
{
if(User.Identity.IsAuthenticated)
{
返回重定向操作(“管理”);
}
if(ModelState.IsValid)
{
//下面是错误System.NullReferenceException:对象引用未设置为对象的实例。
var info=await AuthenticationManager.GetExternalLoginInfoAsync();
if(info==null)
{
返回视图(“外部登录失败”);
}
var user=new ApplicationUser(){UserName=model.UserName};
var result=await UserManager.CreateAsync(用户);
if(result.successed)
{
结果=wait UserManager.AddLoginAsync(user.Id,info.Login);
if(result.successed)
{
等待信号同步(用户,ispersist:false);
返回重定向到本地(returnUrl);
}
}
加法器(结果);
}
ViewBag.ReturnUrl=返回URL;
返回视图(模型);
}

在调试用户名come时,我也无法理解它为什么会抛出异常。

我认为当它到达
GetExternalLoginInfoSync
时,返回null

我也有同样的问题,下面是我如何设法解决它并从Facebook收到电子邮件的

  • 更新以下NuGet包
    • Microsoft.Owin
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.Cookies
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.OAuth
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.Facebook
      至版本
      3.1.0-rc1
然后将以下代码添加到
标识启动

var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);
这是
FacebookBackChannelHandler()
的定义类:

使用系统;
使用System.Net.Http;
公共类FacebookBackChannelHandler:HttpClientHandler
{
受保护的重写异步System.Threading.Tasks.Task SendAsync(
HttpRequestMessage请求,
System.Threading.CancellationToken CancellationToken)
{
//替换RequestUri,使其不会出现格式错误
如果(!request.RequestUri.AbsolutePath.Contains(“/oauth”))
{
request.RequestUri=新Uri(request.RequestUri.AbsoluteUri.Replace(“?访问令牌“,”和访问令牌”);
}
返回wait base.sendaync(请求、取消令牌);
}
}

我认为当它到达
GetExternalLoginInfoSync
时返回null

我也有同样的问题,下面是我如何设法解决它并从Facebook收到电子邮件的

  • 更新以下NuGet包
    • Microsoft.Owin
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.Cookies
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.OAuth
      至版本
      3.1.0-rc1
    • Microsoft.Owin.Security.Facebook
      至版本
      3.1.0-rc1
然后将以下代码添加到
标识启动

var facebookOptions = new FacebookAuthenticationOptions()
        {
            AppId = "your app id",
            AppSecret = "your app secret",
            BackchannelHttpHandler = new FacebookBackChannelHandler(),
            UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email,first_name,last_name",
            Scope = { "email" }
        };

        app.UseFacebookAuthentication(facebookOptions);
这是
FacebookBackChannelHandler()
的定义类:

使用系统;
使用System.Net.Http;
公共类FacebookBackChannelHandler:HttpClientHandler
{
受保护的重写异步System.Threading.Tasks.Task SendAsync(
HttpRequestMessage请求,
System.Threading.CancellationT
var option = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions();
option.AppId = ConfigurationManager.AppSettings.Get("fbAppId");
option.AppSecret = ConfigurationManager.AppSettings.Get("fbAppSecret");
option.Scope.Add("email");
option.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=name,email";
app.UseFacebookAuthentication(option);