任務44:Identity MVC: EF + Identity實現

使用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

修改ApplicationDbContext

同時咱們還須要一個構造函數來接收咱們的DbContextOptions

 

這裏加上ApplicationDbContext

StartUp.cs

註冊Identity

先引入命名空間:

using MvcCookieAuthSample.Data;

再引入命名空間:

using Microsoft.EntityFrameworkCore;

Configuration.GetConnectionString()是來獲取配置文件內配置的數據庫連接字符串

在appsettings.json中本身加上連接字符串:

"ConnectionStrings": {
    "DefaultConnection": "server=.;databse=wjw_core1;uid=sa;pwd=sa;"
  }

 

而後把咱們配置的連接字符串拷貝過來。

 

把Identity加進來

再引入命名空間

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);
        }

 

修改這裏默認的登錄頁面

 

AccountAcontroller中

UserManager是用來建立用戶的

以前咱們的ApplicationUser的單詞進錯了 這裏咱們統一的修改一下

SignInManager主要是用來登錄的

而後這個Action也必須是async的 同時返回的類型用Task去接收

 

加上判斷,若是註冊成功就跳轉到首頁上去

 

9分58秒

這行咱們註冊的代碼就完成了。下面能夠進行代碼的測試

 

密碼暴露了。修改密碼框的類型爲password 。同時確認密碼的字段咱們修改了爲 ConfirmedPassword

從新建立數據庫

經過nuget引入包:Microsoft.EntityFrameworkCore.Tools

 

 

沒有這個包的話 EF的命令是無法用的

11分42秒

執行Migrations

執行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();
        }

 

看一下數據庫內的表 就有了咱們建立的數據了。

完成

相關文章
相關標籤/搜索