【发布时间】:2015-12-27 02:43:32
【问题描述】:
我正在尝试从头开始构建一个简单的登录系统,使用 ASP.NET MVC v5、Entity Framework v7 和 Identity v3 的代码优先方法。我正在使用 Visual Studio 附带的个人用户登录模板在 ASP.NET MVC 应用程序之后对我的应用程序进行建模。
我只想让用户创建一个帐户,并将该帐户保存在数据库中。
这是我到目前为止的代码:
Startup.cs:
public class Startup
{
public IConfigurationRoot Configuration { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseIdentity();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
appsettings.json 包含用于连接数据库的代码:
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=SimpleAuthenticationApp;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
这是 Controllers/AccountController.cs 中 Register POST 操作的代码:
[HttpPost]
public async Task<IActionResult> Register (RegisterViewModel model)
{
try
{
var user = new ApplicationUser { UserName = model.Email };
IdentityResult result = await _userManager.CreateAsync(user, model.Password);
Console.WriteLine(result);
return View("Home", "Index");
}
catch (Exception ex)
{
Console.WriteLine(ex);
return View();
}
}
在此代码中,RegisterViewModel 只是一个 ViewModel,其中包含 Email、Password 和 ConfirmPassword 字段。
Account/Register 视图只是一个要求这些字段的表单。 ApplicationUser 是从 IdentityUser 扩展而来的类。
在POST路由中,我在try块设置断点,进入catch块时,异常读取"Invalid object name AspNetUsers."
在我在这个应用程序中创建第一个用户之前,没有数据库。我注册了一个新用户,应用程序将我带到一个错误页面,显示“为 ApplicationDbContext 应用现有迁移可能会解决此问题”,并带有一个应用迁移的按钮。当我点击按钮时,数据库就创建好了。我注意到,当我使用 Users 应用程序运行默认 MVC 时,有一个 Migrations 文件夹,其中包含 00000000000000_CreateIdentitySchema.cs 和 ApplicationDbContextModelSnapshot.cs就像它们包含创建带有所需表的数据库的设置一样。我尝试在我的应用中使用这些文件,但没有任何区别。
我的问题:
身份/实体框架如何创建带有表的数据库 获取用户信息?我需要“申请”似乎很奇怪 迁移”,然后才能创建应用程序的数据库。
我可以在自己的应用程序中执行哪些操作才能使简单的用户登录正常工作?欢迎使用其他方法或框架。
【问题讨论】:
标签: c# asp.net entity-framework asp.net-mvc-5 asp.net-identity-3