44- EF + Identity实现
阅读原文时间:2023年07月16日阅读:2

1-配置EF, 需要创建如下几个类

默认User主键为guid类型,现在改成int类型

namespace MvcCookieAuthSample.Models
{
public class ApplicationUser:IdentityUser
{

}

namespace MvcCookieAuthSample.Models
{
public class ApplicationUserRole:IdentityRole
{

}  

}

namespace MvcCookieAuthSample.Data
{
public class ApplicationDbContext:IdentityDbContext
{
public ApplicationDbContext(DbContextOptions options):base(options)
{

    }  
}  

}

在Startup.cs 启用EF

public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddDbContext<ApplicationDbContext>(options => {  
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));  
        });  
    }

在appsetting.json配置连接数据字符串

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentitySample-C9275B98-9E63-4E35-AE50-5F96CA59C41D;Trusted_Connection=True;MultipleActiveResultSets=true"
}

使用Nuget增加   Microsoft.EntityFrameworkCore.Tools

然后在控制台运行相关EF命令生成数据库表,  http://www.siyouku.cn/article/6871.html

E:\coding\netcore\MvcCookieAuthSample>dotnet ef migrations add VSInit
E:\coding\netcore\MvcCookieAuthSample>dotnet ef database update

2-启用验证

    public void ConfigureServices(IServiceCollection services)  
    {  
        services.AddDbContext<ApplicationDbContext>(options=> {  
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));  
        });

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)  
            .AddCookie(options=>{//自定义登陆地址,不配置的话则默认为http://localhost:5000/Account/Login  
                options.LoginPath="/Account/Login";  
            });

        services.Configure<CookiePolicyOptions>(options =>  
        {  
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.  
            options.CheckConsentNeeded = context => true;  
            options.MinimumSameSitePolicy = SameSiteMode.None;  
        });

        services.AddIdentity<ApplicationUser, ApplicationUserRole>()  
            .AddEntityFrameworkStores<ApplicationDbContext>()  
            .AddDefaultTokenProviders();

        services.Configure<IdentityOptions>(option=> {  
            option.Password.RequireLowercase = false;  
            option.Password.RequireNonAlphanumeric = false;  
            option.Password.RequireUppercase = false;  
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version\_2\_1);  
    }

注册账号

public class AccountController : Controller
{
private UserManager _userManager;
private SignInManager _signInManager;
public AccountController(UserManager userManager,
SignInManager signInManager)
{
_signInManager = signInManager;
_userManager = userManager;
}

    \[HttpPost\]  
    public async Task<IActionResult> Register(ViewModel.RegisterViewModel registerViewModel)  
    {  
        Models.ApplicationUser applicationUser = new Models.ApplicationUser()  
        {  
            Email = registerViewModel.Email,  
            UserName = registerViewModel.Email,  
            NormalizedEmail = registerViewModel.Email  
        };

        IdentityResult result = await \_userManager.CreateAsync(applicationUser, registerViewModel.Password);  
        if (result.Succeeded)  
        {  
            return RedirectToAction("Index", "Home");  
        }  
        return View();  
    }

}