asp.net core 2.0 Web簡單使用:二、添加預設使用者,修改登入方式__.net

來源:互聯網
上載者:User

後台登入一般懶得用郵箱了,太長,所以改成使用者名稱登入。


首先添加預設使用者

先刪除或移除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);


這個時候,就能夠用使用者名稱而不是郵箱登入了。






相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.