如何在我的自定义表而不是aspnet用户中使用哈希密码保存新记录?

Lea*_*sed 12 c# asp.net asp.net-mvc owin asp.net-identity

我使用asp.net身份创建新用户但收到错误:

无法将值NULL插入列'Id',表'Mydb.dbo.AspNetUsers'; 列不允许空值.INSERT失败.\ r \n语句已终止

但是在这里我没有像AspNetUsers这样的表,而是我拥有自己的用户表.

代码: Web.config:2个连接字符串

 <add name="myEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=;initial catalog=mydb;user id=sa;password=sdfsdfsdf;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
 <add name="MyConnString" connectionString="data source=;initial catalog=Mydb;user id=sa;password=sdfsdfsdf;" providerName="System.Data.SqlClient" />
Run Code Online (Sandbox Code Playgroud)

IdentityModel.cs:

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

        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public virtual string Email { get; set; }
        public string Password { get; set; }
        public string Role { get; set; }
        public Nullable<bool> IsActive { get; set; }
        public Nullable<int> CreatedBy { get; set; }
        public Nullable<System.DateTime> CreatedDate { get; set; }
        public Nullable<System.DateTime> LastLogin { get; set; }

        public ApplicationUser()
        {

        }

        public ApplicationUser(string email, string firstName, string lastName, string designation, bool isActive)
        {
            Email = email;
            FirstName = firstName;
            LastName = lastName;
            Designation = designation;
            IsActive = isActive;
        }
    }
  public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("MyConnString", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
Run Code Online (Sandbox Code Playgroud)

UserStore1.cs:

public class UserStore1 : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>
    {
        private readonly HttpContext _httpContext;
        UserStore<IdentityUser> userStore = new UserStore<IdentityUser>(new ApplicationDbContext());

        public System.Threading.Tasks.Task CreateAsync(ApplicationUser user)
        {
            HttpContext.Current = _httpContext ?? HttpContext.Current;
            var context = userStore.Context as ApplicationDbContext;
           context.Users.Add(user);
           context.Configuration.ValidateOnSaveEnabled = false;
           context.SaveChanges();
            return Task.FromResult(true);
        }
     }
Run Code Online (Sandbox Code Playgroud)

控制器:

     [Authorize]
    public class AccountController : Controller
    {
        public AccountController()
            : this(new UserManager<ApplicationUser>(new UserStore1()))
        {
        }

        public AccountController(UserManager<ApplicationUser> userManager)
        {
            UserManager = userManager;
        }
        public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Login(string email, string password, bool rememberMe = false, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    FirstName= "Abc",
                    LastName= "Pqr",
                    UserName="Abc@yahoo.com",
                    SecurityStamp = Guid.NewGuid().ToString()
                };

                var result= await UserManager.CreateAsync(user,"123456");
            }
            return View();
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:我在数据库表字段中有自动生成的Id,而Id是Int.

更新:我首先使用数据库(edmx),我使用的表是用于插入新记录的自定义表(例如:用户).

起初我已经实现了microsoft asp.net身份,如下面的问题所示,但是1位用户指出我没有使用负责处理登录,cookies等的ApplicationUser类,所以我现在正在尝试使用ApplicationUser类:

如何自定义实现asp.net身份的UpdateAsync方法?

我现在真的很遗憾我决定选择Microsoft Identity Framework进行身份验证,因为我发现它确实很复杂,但现在我已经向前迈进了,我必须继续使用它.

Mah*_*man 6

我发现的不一致,在ApplicationUser课堂上你声明属性Id,Email哪个是错的,因为IdentityUser类已经有了这些属性.这可能会引发这个问题.但是如果需要,你可以覆盖它们.您使用的构造函数也不是必需的.该ApplicationUser班应该是:

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

    public string FirstName { get; set; }
    public string LastName { get; set; }    
    public string Password { get; set; }
    public string Role { get; set; }
    public bool? IsActive { get; set; }
    public int? CreatedBy { get; set; }
    public DateTime? CreatedDate { get; set; }
    public DateTime? LastLogin { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

第二件事,您正在创建内部操作的用户Login也无效.你应该在Register行动中做到这一点.以下是一个例子:

 public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
          var user = new ApplicationUser
            {
                FirstName = "Abc",
                LastName = "Pqr",
                UserName = "Abc@yahoo.com",
                Email= model.Email,
                Password= model.Password,
                PasswordHash = UserManager.PasswordHasher.HashPassword(model.Password),
                SecurityStamp = Guid.NewGuid().ToString()
            };

            var result = await UserManager.CreateAsync(user);
        if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);                    
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        return View(model);
    }
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助:)