我有一个MVC5项目,我一直在关注本教程:
基本上我想使用自己的数据库,而不是使用代码优先的默认方法。我已经完成了所有自定义Store和Identity,但我不知道如何更改我的应用程序以使用我的自定义Context,因为MVC5项目的默认代码使用代码优先行为。
我也对IdentityModels.cs中的代码和Startup中的CreatePerOwinContext感到困惑。有人可以向我解释这个或者给我一个101教程的链接吗?我试过环聊互联网,但我仍然找不到合适的文档/分步教程。
我的自定义UserStore:
public class UserStore : IUserStore<IdentityUser, int>
{
public UserStore() { ... }
public UserStore(MySQLDatabase database) { ... }
public Task CreateAsync(IdentityUser user) { ... }
public Task DeleteAsync(IdentityUser user) { ... }
public Task<IdentityUser> FindByIdAsync(int userId) { ... }
public Task<IdentityUser> FindByNameAsync(string userName) { ... }
public Task UpdateAsync(IdentityUser user) { ... }
public void Dispose() { ... }
}
我的自定义IdentityUser:
public class IdentityUser : IUser<int>
{
public IdentityUser() { ... }
public IdentityUser(string userName) { ... }
public int Id { get; set; }
public string UserName { get; set; }
}
IdentityModels.cs默认代码:
public class ApplicationUser : IdentityUser
{
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);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
启动:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
}
任何帮助将不胜感激。