用于简单注册的asp.net身份验证 - asp.net mvc

时间:2016-07-12 15:40:24

标签: sql-server asp.net-mvc identity

我即将启动一个需要自定义身份验证和授权的项目。

对于身份验证,我问这个问题。

我需要知道如何创建从DBContext类扩展的ExampleDBContext类?以及我需要在Startup.Auth.cs中进行哪些设置才能使其正常工作。对于注册,注册表的名称应该是什么,列应该是什么?还需要哪些其他表格及其列?

有很多与身份验证相关的信息,但没有任何实际用处。感谢

1 个答案:

答案 0 :(得分:0)

我不确定,但我认为你想要这样的事情:

<强> ExampleDbContext.cs

public class ExampleDbContext : IdentityDbContext<User>, IExampleDbContext
{
    public ExampleDbContext()
        : base("yourConnectionStringName", throwIfV1Schema: false)
    {
    }

    public static ExampleDbContext Create()
    {
        return new ExampleDbContext();
    }



    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<User>().ToTable("Users");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
    }

    void IDisposable.Dispose()
    {
        this.Dispose();
    }
}

您可以使用代码优先方法生成表格。这意味着您可以按照自己的方式自定义用户模型。这是

的例子

<强> User.cs

public class User : IdentityUser
{
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> 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 string FirstName { get; set; }
        public string LastName { get; set; }
}

在用户中,您可以看到我添加了一些自定义字段(FirstName LastName),如果您首先使用该代码,则可以生成自定义Users表并将其用于身份验证。无需在Startup.Auth.cs中添加任何内容,只需正确设置依赖注入即可。