【发布时间】:2019-09-06 15:03:28
【问题描述】:
我已经尝试了所有可以在 SO 上找到的答案。我正在尝试将 Identity 添加到我的 ASP.NET MVC 5 项目中。我首先使用数据库。已经有一个现有的数据库。我使用此 GitHub 中的脚本在我的数据库中创建身份表。
https://gist.github.com/jeroenheijmans/8fa79427abc25a864cb055616644172f
这是我的 Startup.cs 文件
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new AppDbContext());
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<RoleManager<AspNetRole>>((options, context) =>
new RoleManager<AspNetRole>(
new RoleStore<AspNetRole>(context.Get<AppDbContext>())));
app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
这是我的 ApplicationUserManager:
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new AppDbContext());
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<RoleManager<AspNetRole>>((options, context) =>
new RoleManager<AspNetRole>(
new RoleStore<AspNetRole>(context.Get<AppDbContext>())));
app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
}
这是我的注册操作:
public async Task<ActionResult> Register()
{
var model = (RegisterUserModel)Session["RegisterAccount"];
var user = new AspNetUser()
{
UserName = model.Email,
Email = model.Email
};
var userManager = Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
IdentityResult addUserResult = await userManager.CreateAsync(user, model.Password);
}
我的角色类
public partial class AspNetRole : IdentityRole
{
public AspNetRole(string name) { Name = name; }
}
我的用户类
public partial class AspNetUser : IdentityUser
{
}
我的数据库上下文
public partial class AppDbContext: IdentityDbContext<AspNetUser>
{
public AppDbContext(string connectionString)
: base(connectionString)
{}
}
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-identity identity