用户标识未发现ASPNET标识错误的GenerateUserIdentityAsync方法 [英] UserId not found error in aspnet Identity at GenerateUserIdentityAsync method

查看:1299
本文介绍了用户标识未发现ASPNET标识错误的GenerateUserIdentityAsync方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在注册一个用户,也login.Moreoever后,登记后,数据被保存到数据库中dbo.AspNetUsers表后获取用户ID未找到错误,ID列自动递增,并返回类型为int。
有一个在AspNetUserClaims table.It Userid列有4个山口---编号,用户ID,ClaimType,ClaimValue.It具有ID列自动递增而不是用户标识。

我最初成功更改主键从字符串到int通过以下链接--- <一href=\"http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity\" rel=\"nofollow\">http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity.

它已成功运行之前,但现在它给我在这行错误---

 公共异步任务&LT; ClaimsIdentity&GT; GenerateUserIdentityAsync(的UserManager&LT; ApplicationUser,INT&GT;经理)
    {
        //注意authenticationType必须CookieAuthenticationOptions.AuthenticationType定义的匹配
        VAR的UserIdentity =等待manager.CreateIdentityAsync(这一点,DefaultAuthenticationTypes.ApplicationCookie);
        //添加自定义的用户在这里声明
        返回的UserIdentity;
    }

异常详细信息:System.InvalidOperationException:用户ID未找到
这是完整的堆栈跟踪。你可以在这里看到它---- http://pastebin.com/0hp5eAnp

这是罚款早些时候工作,但现在,当我加入其他表的外键关系,我不知道什么是缺少那里。在数据库中有他们,但缺少的东西在这里之间的正确关系,正确创建的所有表。

我的ApplicationUser类是这样-------

 公共类ApplicationUser:IdentityUser&LT; INT,CustomUserLogin,CustomUserRole,CustomUserClaim&GT;
 {
    公共ApplicationUser()
    {
        this.Posts =新的HashSet&LT;邮政&GT;();
    }
    [键]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)
    公众诠释标识{搞定;组; }
    公共虚拟的ICollection&LT;邮政和GT;帖子{搞定;组; }
    公共异步任务&LT; ClaimsIdentity&GT; GenerateUserIdentityAsync(的UserManager&LT; ApplicationUser,INT&GT;经理)
    {
        //注意authenticationType必须CookieAuthenticationOptions.AuthenticationType定义的匹配
        VAR的UserIdentity =等待manager.CreateIdentityAsync(这一点,DefaultAuthenticationTypes.ApplicationCookie);
        //添加自定义的用户在这里声明
        返回的UserIdentity;
    }
    公共类CustomUserRole:IdentityUserRole&LT; INT&GT; {}
    公共类CustomUserClaim:IdentityUserClaim&LT; INT&GT; {}
    公共类CustomUserLogin:IdentityUserLogin&LT;&诠释GT; {}    公共类CustomRole:IdentityRole&LT; INT,CustomUserRole&GT;
   {
    公共CustomRole(){}
    公共CustomRole(字符串名称){名称=名称; }
}公共类CustomUserStore:UserStore&LT; ApplicationUser,CustomRole,INT,
    CustomUserLogin,CustomUserRole,CustomUserClaim&GT;
{
    公共CustomUserStore(ApplicationDbContext上下文)
        :基座(上下文)
    {
    }
}公共类CustomRoleStore:Rolestore的&LT; CustomRole,INT,CustomUserRole&GT;
{
    公共CustomRoleStore(ApplicationDbContext上下文)
        :基座(上下文)
    {
    }
}

我IdentityConfig.cs类文件是这样的-------

  //配置在这个应用中使用的应用程序用户管理器。的UserManager在ASP.NET的身份定义,用于应用程序。
公共类ApplicationUserManager:&的UserManager LT; ApplicationUser,INT&GT;
{
    公共ApplicationUserManager(IUserStore&LT; ApplicationUser,INT&GT;存储)
        :基地(存储)
    {
    }    公共静态ApplicationUserManager创建(IdentityFactoryOptions&LT; ApplicationUserManager&gt;选项,IOwinContext上下文)
    {
        VAR经理=新ApplicationUserManager(新CustomUserStore(context.Get&LT; ApplicationDbContext&GT;()));
        //配置用户名验证逻辑
        manager.UserValidator =新UserValidator&LT; ApplicationUser,INT&GT;(经理)
        {
            AllowOnlyAlphanumericUserNames =假,
            RequireUniqueEmail =真
        };        //配置密码验证逻辑
        manager.PasswordValidator =新PasswordValidator
        {
            RequiredLength = 1,
            // RequireNonLetterOrDigit = TRUE,
            // RequireDigit = TRUE,
            // RequireLowercase = TRUE,
            // RequireUppercase = TRUE,
        };        //配置用户锁定默认
        manager.UserLockoutEnabledByDefault = TRUE;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;        //注册双因素身份验证提供者。此应用程序使用手机和电子邮件作为接收code用于验证用户的步骤
        //你可以写自己的供应商,并在这里插入。
        manager.RegisterTwoFactorProvider(手机code,新PhoneNumberTokenProvider&LT; ApplicationUser,INT&GT;
        {
            MessageFormat =您的安全code是{0}
        });
        manager.RegisterTwoFactorProvider(电子邮件code,新EmailTokenProvider&LT; ApplicationUser,INT&GT;
        {
            主题=安全code,
            BodyFormat =您的安全code是{0}
        });
        manager.EmailService =新EmailService();
        manager.SmsService =新SmsService();
        VAR dataProtectionProvider = options.DataProtectionProvider;
        如果(dataProtectionProvider!= NULL)
        {
            manager.UserTokenProvider =
                新DataProtectorTokenProvider&LT; ApplicationUser,INT&GT;(dataProtectionProvider.Create(ASP.NET身份));
        }
        返回经理;
    }
}//配置应用程序登录管理器,它是本应用中使用。
公共类ApplicationSignInManager:SignInManager&LT; ApplicationUser,INT&GT;
{
    公共ApplicationSignInManager(ApplicationUserManager的UserManager,IAuthenticationManager AuthenticationManager会)
        :基地(的UserManager,AuthenticationManager会)
    {
    }    公共覆盖任务&LT; ClaimsIdentity&GT; CreateUserIdentityAsync(ApplicationUser用户)
    {
        返回user.GenerateUserIdentityAsync((ApplicationUserManager)的UserManager);
    }    公共静态ApplicationSignInManager创建(IdentityFactoryOptions&LT; ApplicationSignInManager&gt;选项,IOwinContext上下文)
    {
        返回新ApplicationSignInManager(context.GetUserManager&LT; ApplicationUserManager&GT;(),context.Authentication);
    }
}

我见过很多计算器的答案,但没有得到它work.Can有人plzz plzz看缺什么,我应该怎么办now.thanks提前。
在此,在applicationUser类,在Id列,它示出在这样的工具提示一些警告和消息-------
      models.ApplicationUSer.ID隐藏继承的成员
       Microsoft.Aspnet.Identity.EntityFramework.IDentity
       用户名。为了使当前成员覆盖
该实现,加上override关键字,否则
添加新的关键字
其中x是刚刚的命名空间。

我在App_Start文件夹StartUp.Auth.cs是这样的------

 公共部分类启动
    {
     公共无效ConfigureAuth(IAppBuilder应用程序)
     {
        //配置分贝范围内,用户管理和登入管理器使用每个请求的单个实例
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext&LT; ApplicationUserManager&GT;(ApplicationUserManager.Create);
        app.CreatePerOwinContext&LT; ApplicationSignInManager&GT;(ApplicationSignInManager.Create);        //使应用程序能够使用cookie来存储信息,在用户签订
        //并利用co​​okie来临时存储有关用户记录的信息与第三方供应商登录
        //配置在cookie中的标志
        app.UseCookieAuthentication(新CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LOGINPATH =新PathString(/帐号/登录),
            供应商=新CookieAuthenticationProvider
            {
                //允许应用验证安全戳当用户登录英寸
                //这是一项安全功能,当您更改密码或添加外部登录到您的帐户被使用。
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&LT; ApplicationUserManager,ApplicationUser,INT&GT;(
                    validateInterval:TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback:(经理,用户)=&GT; user.GenerateUserIdentityAsync(经理),getUserIdCallback:(ID)=&GT;(id.GetUserId&LT; INT&GT;()))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);        //使应用程序能够临时存储时,他们正在核实在双因素身份验证过程的第二个因素用户信息。
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie,TimeSpan.FromMinutes(5));        //使应用程序能够记住第二次登录验证的因素,如电话或电子邮件。
        //一旦选中此选项,在登录过程中验证的第二个步骤将是你从登录的设备记住。
        //这是类似的,当你登录了rememberMe选项。
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);        //取消注释以下行来实现与第三方供应商登录登录
        //app.UseMicrosoftAccountAuthentication(
        //的clientId:,
        // clientSecret:); .......................................... ............................

和我startUp.cs文件是这样的----

  [汇编:OwinStartupAttribute(typeof运算(WebApp.Startup))]
   Web应用程序的命名空间
   {
    公共部分类启动
   {
    公共无效配置(IAppBuilder应用程序)
    {
        ConfigureAuth(应用);
    }
   }
  }


解决方案

您将不得不拿出你的ApplicationUserManager有它非常干净,并实现更多的方法......例如见下后(这与实现所有方法的自定义键(在本例中TKEY的):

<一个href=\"http://www.symbolsource.org/MyGet/Metadata/aspnetwebstacknightly/Project/Microsoft.AspNet.Identity.Core/2.0.0-beta1-140211/Release/Default/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core/UserManager.cs?ImageName=Microsoft.AspNet.Identity.Core\" rel=\"nofollow\">http://www.symbolsource.org/MyGet/Metadata/aspnetwebstacknightly/Project/Microsoft.AspNet.Identity.Core/2.0.0-beta1-140211/Release/Default/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core/UserManager.cs?ImageName=Microsoft.AspNet.Identity.Core

您将看到错误,您收到的 GetSecurityStampAsync 也有实施

I am getting UserId not found error after registring a user and also after login.Moreoever, after registration, data is saved to database and in dbo.AspNetUsers table, id column is auto incremented and return type is int. There is UserId Column in AspNetUserClaims table.It has 4 Col---Id,UserId,ClaimType,ClaimValue.It has Id column as auto incremented not the userId. I was initially successfully changed Primary key from string to int by following this link---http://www.asp.net/identity/overview/extensibility/change-primary-key-for-users-in-aspnet-identity.

It was running succesfully before but now it is giving me error at this line---

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

Exception Details: System.InvalidOperationException: UserId not found. This is the complete stack trace. you can see it here----http://pastebin.com/0hp5eAnp

It was working fine earlier but now when i added foreign key relationship with other tables, i don't know what is missing there. In the database all the tables are created properly with proper relationship between them but something is missing here.

My ApplicationUser class is something like this-------

 public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole, CustomUserClaim>
 {
    public ApplicationUser()
    {
        this.Posts = new HashSet<Post>();
    }
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
    public class CustomUserRole : IdentityUserRole<int> { }
    public class CustomUserClaim : IdentityUserClaim<int> { }
    public class CustomUserLogin : IdentityUserLogin<int> { }

    public class CustomRole : IdentityRole<int, CustomUserRole>
   {
    public CustomRole() { }
    public CustomRole(string name) { Name = name; }
}

public class CustomUserStore : UserStore<ApplicationUser, CustomRole, int,
    CustomUserLogin, CustomUserRole, CustomUserClaim>
{
    public CustomUserStore(ApplicationDbContext context)
        : base(context)
    {
    }
}

public class CustomRoleStore : RoleStore<CustomRole, int, CustomUserRole>
{
    public CustomRoleStore(ApplicationDbContext context)
        : base(context)
    {
    }
} 

and my IdentityConfig.cs class file is something like this-------

     // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new CustomUserStore(context.Get<ApplicationDbContext>()));
        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };

        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 1,
            //RequireNonLetterOrDigit = true,
            //RequireDigit = true,
            //RequireLowercase = true,
            //RequireUppercase = true,
        };

        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;

        // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
        // You can write your own provider and plug it in here.
        manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser, int>
        {
            MessageFormat = "Your security code is {0}"
        });
        manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser, int>
        {
            Subject = "Security Code",
            BodyFormat = "Your security code is {0}"
        });
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider = 
                new DataProtectorTokenProvider<ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

// Configure the application sign-in manager which is used in this application.
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

i have seen many stackoverflow answers but not getting it to work.Can someone plzz plzz see what is missing, what should i do now.thanks in advance. Here, in the applicationUser class, at the Id column, it showing some warning and message in tooltip like this------- models.ApplicationUSer.ID hides inherited member Microsoft.Aspnet.Identity.EntityFramework.IDentity USer.Id. To make current member override that implementation, add override keyword otherwise add new keyword where x is just the namespace.

My StartUp.Auth.cs in App_Start folder is like this------

     public partial class Startup
    {
     public void ConfigureAuth(IAppBuilder app)
     {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager), getUserIdCallback:(id)=>(id.GetUserId<int>()))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");......................................................................

and my startUp.cs file is like this----

   [assembly: OwinStartupAttribute(typeof(WebApp.Startup))]
   namespace WebApp
   {
    public partial class Startup
   {
    public void Configuration(IAppBuilder app)
    {
        ConfigureAuth(app);
    }
   }
  }

解决方案

You will have to pull out your ApplicationUserManager to have it nice and clean and implement more methods... For example see following post (It implemented all methods with your custom Key (TKey in the example):

http://www.symbolsource.org/MyGet/Metadata/aspnetwebstacknightly/Project/Microsoft.AspNet.Identity.Core/2.0.0-beta1-140211/Release/Default/Microsoft.AspNet.Identity.Core/Microsoft.AspNet.Identity.Core/UserManager.cs?ImageName=Microsoft.AspNet.Identity.Core

You will see that the error you receive GetSecurityStampAsync also is implemented there.

这篇关于用户标识未发现ASPNET标识错误的GenerateUserIdentityAsync方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆