繁体   English   中英

SignInManager.PasswordSignInAsync 抛出空对象异常

[英]SignInManager.PasswordSignInAsync Throwing Null Object Exception

AccountController.cs包含AccountController类。 该类的Login方法失败。 具体来说,

var result = await SignInManager.PasswordSignInAsync(
    model.Email, model.Password, model.RememberMe, shouldLockout: true);

Login方法中抛出System.NullReferenceException

我已经验证了model.Emailmodel.Passwordmodel.RememberMe不为空。 下一步是深入到SignInManager ,它是AccountControllerApplicationSignInManager类型的一个对象。 从上一行调用的SignInManagerget访问器是

public ApplicationSignInManager SignInManager
{
    get
    {
        return _signInManager ??
            HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
    }
    // private set...
}

我改写为

public ApplicationSignInManager SignInManager
{
    get
    {
        var c = HttpContext.GetOwinContext();
        var m = c.Get<ApplicationSignInManager>();
        return _signInManager ?? m;
    }
    // private set...
}

调试并确保get访问器没有返回null 它没有返回null 这告诉我PasswordSignInAsync需要的东西是null

我查看了PasswordSignInAsync 的来源,它在防止空引用错误方面做得非常好。 我还深入研究了PasswordSignInAsync调用的方法。 我只是看不到什么可能会引发空引用错误。

错误的堆栈跟踪非常神秘,我看不出其中有任何帮助。 但为了完整起见,这里是:

[NullReferenceException: Object reference not set to an instance of an object.]
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +2112
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +123
Microsoft.AspNet.Identity.Owin.<SignInAsync>d__2.MoveNext() +408
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Microsoft.AspNet.Identity.CultureAwaiter.GetResult() +63
Microsoft.AspNet.Identity.Owin.<SignInOrTwoFactor>d__23.MoveNext() +2055
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +68
Microsoft.AspNet.Identity.Owin.<PasswordSignInAsync>d__29.MoveNext() +1828
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
ApexRemingtonExternal.Controllers.<Login>d__2.MoveNext() in c:\Users\me\sc\project\Controllers\AccountController.cs:91
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

我很感激有关可能导致此NullReferenceException原因的任何帮助或指导。 如果我可以添加更多细节(或删除一些(笑!)),请告诉我。 这是我和我公司的第一个 MVC 项目,所以我确定我已经破坏了一些东西。

编辑

我应该补充一点,我从项目中剥离了实体框架,转而使用 LINQ to SQL,这是我们在所有其他项目中所依赖的。 这意味着我必须实现我自己的 IUserStore、IRoleStore 等版本。

有时(特别是如果您更新Microsoft.AspNet.Identity.Owin )您可能会忘记添加行

app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

方法public void ConfigureAuth(IAppBuilder app)App_Start\\Startup.Auth.cs包含此后一切都应该工作。

正如我通常习惯的那样,这个问题与症状无关。 当然SignInManager.PasswordSignInAsync没有坏。 是我的代码被破坏了。 这使得这个问题没有实际意义,这恳求我删除这个问题。

然而,这里有一个教训需要吸取。 就我而言,它是as关键字。 正如编辑中提到的那样,放弃了 EF,我不得不提供几个接口的实现。 我必须提供的一种方法是GetRolesAsync ,它返回Task<IList<String>> (在我的情况下)。 我从来没有处理过IList 原来, as正是我需要的。 但是我试图将IQueryable转换为IList ,但这不起作用。 结果: as简单地返回null 谢谢, as 这很有用。

是的。 我可能会删除这个问题。

玩的有点晚了,但是今天遇到这个错误,发现空引用异常的原因是ApplicationUser里面的null属性。

当您在 Applicationuser 中创建自定义声明时会发生这种情况。 当您调用SignInManager.PasswordSignInAsync ,它将 GenerateUserIdentity 并包括您的自定义声明。 那里的任何空对象都会抛出 NULL REFERENCE EXCEPTION。

显示一些示例代码(请参阅注释):

public class ApplicationUser : IdentityUser
{
    ...//some additional properties goes here

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

        //my custom claims
        List<Claim> claims = new List<Claim>
        {
            new Claim("FirstName", FirstName.ToString()),
            new Claim("MiddleName", MiddleName.ToString()),
            new Claim("LastName", LastName.ToString()),
            new Claim("Position", Position.ToString()) //if Position is NULL, it will throw null reference exception
        };

        userIdentity.AddClaims(claims);

        return userIdentity;
    }
}

我希望这会在将来对某人有所帮助。

就我而言,它是数据!

我在我的测试数据库中手动将TwoFactorEnabled的值设置为 true,并且对于该特定用户PhoneNumber为 null, PhoneNumberConfirmed设置为 false。 插入值PhoneNumber和标记PhoneNumberConfirmed作为真正做出异常消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM