asp.net core 2.0 Web简单使用:二、添加默认用户,修改登录方式

后台登录一般懒得用邮箱了,太长,所以改成用户名登录。


首先添加默认用户

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


这个时候,就能够用用户名而不是邮箱登录了。






评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值