1. 程式人生 > 實用技巧 ><一>初試Identity

<一>初試Identity

搞理論之前先把identity配置起來。

1、新建一個mvc專案
2、引入Identity.EntityFrameworkCore,EntityFrameworkCore,EntityFrameworkCore.sqlserver,EntityFrameworkCore.Tools
3、配置資料庫連線
4、配置資料庫上下文

1、配置資料庫連線

 "ConnectionStrings": {
    "conn": "Data Source=127.0.0.1;User ID=sa;Password=62;database=IdentityTest;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False
" }

2、注入管道

  services.AddDbContext<ApplicationDbContext>(options =>
            {
                //配置檔案前面必須是;ConnectionStrings
                //因為預設是:GetSection("ConnectionStrings")[name].
                 options.UseSqlServer(Configuration.GetConnectionString("conn"));
                //options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
}); services.AddIdentity<ApplicationUser, ApplicationRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders();

3、配置資料庫上下文

namespace IdentityTest.Data
{
    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } }

4、新增相關模型類

 public class ApplicationRole: IdentityRole
    {
    }
  public class ApplicationUser: IdentityUser
    {
    }
 public class RegisterViewModel
    {
        public string UserName { get; set; }

        public string PassWord { get; set; }
    }

5、新增Login的Controller

 public class LoginController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signinManager;
        public LoginController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signinManager)
        {
            _userManager = userManager;
            _signinManager = signinManager;
        }
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel model)
        {
            var identityUser = new ApplicationUser
            {
                UserName = model.UserName,
                PasswordHash = model.PassWord,
                NormalizedEmail = model.UserName
            };

            var identityResult = await _userManager.CreateAsync(identityUser, model.PassWord);
            if (identityResult.Succeeded)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

    }

6、新增Index.cshtml的註冊頁面

<div>

    <form asp-controller="Login" asp-action="Register" method="post">

        <div>

            <label class="control-label">使用者名稱</label>

            <input class="form-control" type="text" name="UserName" />

        </div>

        <div>

            <label class="control-label">密碼</label>

            <input class="form-control" type="password" name="PassWord" />

        </div>

        <div class="form-group">

            <input type="submit" value="登入" class="btn btn-primary" />

        </div>
    </form>

</div>

7、資料庫遷移,控制檯執行如下命令

1、 Add-Migration
2、 Update-Database 

8、執行完後資料庫會生成如下表

9、執行註冊頁面點選註冊成功後,資料庫登錄檔會生成一條test的賬戶,就此,identity的配置就成功了