如何保存新记录与散列密码在我的自定义表,而不是aspnet用户
本文关键字:自定义 我的 用户 aspnet 密码 保存 何保存 新记录 | 更新日期: 2023-09-27 18:05:22
我正在使用asp.net身份创建新用户,但得到错误:
不能在表列'Id'中插入NULL值"Mydb.dbo.AspNetUsers";列不允许为空。插入失败。'r'n语句已被终止
但是这里我没有任何像AspNetUsers这样的表,而是有我自己的表Users。
代码: 网络。config: 2个连接字符串
<add name="myEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=mydb;user id=sa;password=sdfsdfsdf;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="MyConnString" connectionString="data source=;initial catalog=Mydb;user id=sa;password=sdfsdfsdf;" providerName="System.Data.SqlClient" />
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();
}
}
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);
}
}
控制器:
[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();
}
}
注意:我已经自动生成Id在我的数据库表字段,Id是Int.
更新:我首先使用数据库(edmx),我使用的表是用于插入新记录的自定义表(例如:Users)。
首先,我已经实现了微软asp.net身份如下所示的问题,但1用户指出,我没有使用ApplicationUser类,它负责处理登录,cookie 等,所以我现在试图使用ApplicationUser类:
如何给asp.net身份的UpdateAsync方法的自定义实现?
我现在真的很后悔当初选择微软身份认证框架,因为我发现它很复杂,但现在随着我的发展,我不得不继续使用它。
我发现的不一致,在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; }
}
第二件事,您正在Login
操作中创建用户,这也是无效的。你应该在Register
action里面做。以下示例:
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);
}
希望对你有帮助