使用VSCode开发 Razer的智能感知很差。因此这里切换为VS2017进行开发:sql
新建一个Data的文件夹来存放咱们的DBContext。在Data文件夹下新建:数据库
ApplicationDbContext.csjson
继承:IdentityDbContext在using Microsoft.AspNetCore.Identity.EntityFrameworkCore;的命名空间下面cookie
而后在Models里面建立两个实体类:app
ApplicaationUser和ApplicationUserRoleasync
ApplicaationUser.cs内继承IdentityUser在命名空间using Microsoft.AspNetCore.Identity;下ide
若是咱们想改主键的类型为guid的话,就须要给他一个泛型的参数函数
这里咱们设置主键的类型为int类型的测试
ApplicationUserRole继承:IdentityRole<int>ui
同时咱们还须要一个构造函数来接收咱们的DbContextOptions
这里加上ApplicationDbContext
先引入命名空间:
using MvcCookieAuthSample.Data;
再引入命名空间:
using Microsoft.EntityFrameworkCore;
Configuration.GetConnectionString()是来获取配置文件内配置的数据库连接字符串
在appsettings.json中本身加上连接字符串:
"ConnectionStrings": { "DefaultConnection": "server=.;databse=wjw_core1;uid=sa;pwd=sa;" }
而后把咱们配置的连接字符串拷贝过来。
再引入命名空间
using Microsoft.AspNetCore.Identity;
密码限制
在identity下有一些默认的密码的限制,会很严格,这里咱们改一下:
这样最终的代码
public void ConfigureServices(IServiceCollection services) { // 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.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); }); services.AddIdentity<ApplicaationUser, ApplicationUserRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options=>{ options.LoginPath="/Account/Login"; }); services.Configure<IdentityOptions>(options => { options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); }
修改这里默认的登录页面
UserManager是用来建立用户的
以前咱们的ApplicationUser的单词进错了 这里咱们统一的修改一下
SignInManager主要是用来登录的
而后这个Action也必须是async的 同时返回的类型用Task去接收
加上判断,若是注册成功就跳转到首页上去
9分58秒
这行咱们注册的代码就完成了。下面能够进行代码的测试
密码暴露了。修改密码框的类型为password 。同时确认密码的字段咱们修改了为 ConfirmedPassword
经过nuget引入包:Microsoft.EntityFrameworkCore.Tools
没有这个包的话 EF的命令是无法用的
11分42秒
执行EF的migrations命令报了个错误
上面写着让我用dotnet ef migrations remove方法。而后我就用了一下,而后就报了一个错误。发现应该是连接字符串的单词拼写错了
以前这的单词拼写错了。将连接字符串拼成正确的
打开sql server 局看到建立好的数据库了。
运行页面执行注册。在AccountController里面加断点测试程序是否执行成功了。
这是注册成功的效果:
正常跳转是跳转到首页。这里跳转的地方,应该前面是是Action 后面是Home的控制器。上面代码我写反了 进行修正。
public async Task<IActionResult> Register(RegisterViewModel registerViewModel) { var identityUser = new ApplicationUser() { Email=registerViewModel.Email, UserName=registerViewModel.Email, NormalizedEmail=registerViewModel.Email }; var identityResult = await _userManager.CreateAsync(identityUser, registerViewModel.Password); if (identityResult.Succeeded) { return RedirectToAction("Index", "Home"); } return View(); }
看一下数据库内的表 就有了咱们建立的数据了。