ASP.NET Identity 3.0-如何在MVC应用程序中创建包含用户表的数据库

本文关键字:包含 创建 用户 数据库 应用程序 MVC Identity NET ASP | 更新日期: 2023-09-27 18:28:04

我正在尝试从头开始构建一个简单的登录系统,使用ASP.NET MVC v5、Entity Framework v7和Identity v3的代码优先方法。我正在用VisualStudio附带的带有个人用户登录模板的ASP.NET MVC应用程序来建模我的应用程序。

我只想让用户创建一个帐户,并将该帐户保存在数据库中。

这是我迄今为止的代码:

启动.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:中注册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视图只是一个请求这些字段的表单。CCD_ 2是从CCD_ 3扩展而来的类。

在POST路由中,我在try块设置了一个断点,当它进入catch块时,异常读取"无效对象名AspNetUsers"

在我在此应用程序中创建第一个用户之前,没有数据库。我注册了一个新用户,应用程序将我带到一个错误页面,上面写着"为ApplicationDbContext应用现有迁移可能会解决这个问题",并带有应用迁移的按钮。当我按下按钮时,数据库就创建了。我注意到,当我运行默认的MVC with Users应用程序时,有一个Migrations文件夹,其中包含00000000000000_CreateIdentitySchema.csApplicationDbContextModelSnapshot.cs,看起来它们包含创建具有所需表的数据库的设置。我试着在我的应用程序中使用这些文件,但没有任何区别。

我的问题:

  • Identity/Entity Framework如何创建带有表的数据库获取用户信息?我需要"申请",这似乎很奇怪迁移",然后才能创建应用程序的数据库。

  • 我可以在自己的应用程序中做些什么来让简单的用户登录正常工作?欢迎采用其他方法或框架。

ASP.NET Identity 3.0-如何在MVC应用程序中创建包含用户表的数据库

EntityFramework使用连续迁移概念在需要时升级数据库架构。默认情况下,初始迁移会创建您已经发现的用户/身份表。您不必直接对Migrations文件夹中的代码执行任何操作;如果您设置了迁移初始化程序,则可以在启动时初始化/升级数据库:

我建议你通读这篇简介,以更好地了解正在发生的事情以及你可以用它做什么:

https://msdn.microsoft.com/en-us/data/jj591621.aspx

本文介绍了我上面提到的自动初始化/升级场景。

老实说,我不得不在这里写一篇关于这方面的长文:https://medium.com/@goodealsnow/asp-net-core-identity3-0-6018fc151b4通常,您可以使用dotnet cli来部署迁移dotnet ef迁移添加Version2CoolWaves-o Data''migrations

但请阅读我的完整文章,了解循序渐进的教程。