後台登入一般懶得用郵箱了,太長,所以改成使用者名稱登入。
首先添加預設使用者
先刪除或移除Data目錄下的Migrations目錄及其下面的內容
在Data目錄下添加類DbInitializer,用於添加預設使用者,其中context後面會用就一起加了。
預設使用者許可權包括admin和user
預設使用者名是admin,密碼是abc123
using Microsoft.AspNetCore.Identity;using RCKohi.Models;using System.Linq;using System.Threading.Tasks;namespace RCKohi.Data{ public class DbInitializer { public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager,RoleManager<IdentityRole> roleManager) { context.Database.EnsureCreated(); if (context.Users.Any()) { return; // DB has been seeded } await CreateDefaultUserAndRole(userManager, roleManager); } private static async Task CreateDefaultUserAndRole(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager) { string roleAdmin = "admin"; string roleUser = "user"; await CreateDefaultRole(roleManager, roleAdmin); await CreateDefaultRole(roleManager, roleUser); var user = await CreateDefaultUser(userManager); await AddDefaultRoleToDefaultUser(userManager, roleAdmin, user); await AddDefaultRoleToDefaultUser(userManager, roleUser, user); } private static async Task CreateDefaultRole(RoleManager<IdentityRole> roleManager, string role) { await roleManager.CreateAsync(new IdentityRole(role)); } private static async Task<ApplicationUser> CreateDefaultUser(UserManager<ApplicationUser> userManager) { var user = new ApplicationUser { Email = "5140075@qq.com", UserName = "admin" }; await userManager.CreateAsync(user,"abc123"); var createdUser = await userManager.FindByEmailAsync("5140075@qq.com"); return createdUser; } private static async Task AddDefaultRoleToDefaultUser(UserManager<ApplicationUser> userManager, string role, ApplicationUser user) { await userManager.AddToRoleAsync(user, role); } }}
修改ApplicationDbContext類,啟用模型優先方式
using System.Threading.Tasks;using Microsoft.AspNetCore.Identity.EntityFrameworkCore;using Microsoft.EntityFrameworkCore;using RCKohi.Models;namespace RCKohi.Data{ public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<RCKohi.Models.ApplicationUser> ApplicationUser { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Customize the ASP.NET Identity model and override the defaults if needed. // For example, you can rename the ASP.NET Identity table names and more. // Add your customizations after calling base.OnModelCreating(builder); } }}
修改Program類,讓啟動的時候,運行DbInitializer,並把資料庫上下文傳遞過去
using Microsoft.AspNetCore;using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Identity;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using RCKohi.Data;using RCKohi.Models;using System;namespace RCKohi{ public class Program { public static void Main(string[] args) { //BuildWebHost(args).Run(); var host = BuildWebHost(args); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<ApplicationDbContext>(); var userManager = services.GetRequiredService<UserManager<ApplicationUser>>(); var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>(); DbInitializer.Initialize(context, userManager, roleManager).Wait(); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while seeding the database."); } } host.Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); }}
做完以上內容,啟動的時候,如果資料庫中沒有對應的表就會建立資料庫表和資料。
修改登入方式
修改LoginViewModel,將Email修改為UserName
[Required] [DataType(DataType.Text)] public string UserName { get; set; }
修改對應視圖Login.cshtml,將Email修改為UserName
<div class="form-group"> <label asp-for="UserName"></label> <input asp-for="UserName" class="form-control" /> <span asp-validation-for="UserName" class="text-danger"></span> </div>
修改AccountController控制器的login方法,將Email修改為UserName
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
這個時候,就能夠用使用者名稱而不是郵箱登入了。