From Zero

Asp.net Core 2.0
空白專案

Add appsettings.json
{
"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=MyDb;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Cerate Model Folder
Add ApplicationUser.cs
   public class ApplicationUser :IdentityUser
    {

        public ApplicationUser()
       : base()
        {
        }

        public ApplicationUser(string userName, string firstName, string lastName, DateTime birthDay)
            : base(userName)
        {
            base.Email = userName;

            this.FirstName = firstName;
            this.LastName = lastName;
            this.BirthDay = birthDay;

        }


        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }

        [Required]
        [DataType(DataType.Date)]
        public DateTime BirthDay { get; set; }

        public string FullName => $"{this.FirstName} {this.LastName}";
    }

Create Data Foleder
Add ApplicationDbContext.cs

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

using WebApplication1.Models;


public class ApplicationDbContext :IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
           : base(options)
        {
        }

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


Modify Startup.cs
using Microsoft.Extensions.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;


public Startup(IConfiguration configuration )
        {Configuration = configuration; }

public IConfiguration Configuration { get; }

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddMvc();
        }

modify .csproj
<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
  </ItemGroup>

Dos command 
dotnet ef migrations add initial
dont ef database update


Data Folder
Create DbInitializer.cs


public class DbInitializer
    {
        public static async Task Initialize(ApplicationDbContext context, UserManager<ApplicationUser> userManager,
            RoleManager<IdentityRole> roleManager)
        {
            context.Database.EnsureCreated();

            // Look for any users.
            if (context.Users.Any())
            {
                return; // DB has been seeded
            }

            await CreateDefaultUserAndRoleForApplication(userManager, roleManager);
        }

        private static async Task CreateDefaultUserAndRoleForApplication(UserManager<ApplicationUser> um, RoleManager<IdentityRole> rm)
        {
            const string administratorRole = "Administrator";
            const string email = "noreply@your-domain.com";

            await CreateDefaultAdministratorRole(rm, administratorRole);
            var user = await CreateDefaultUser(um, email);
            await SetPasswordForDefaultUser(um, email, user);
            await AddDefaultRoleToDefaultUser(um, email, administratorRole, user);
        }

        private static async Task CreateDefaultAdministratorRole(RoleManager<IdentityRole> rm, string administratorRole)
        {
            //logger.LogInformation($"Create the role `{administratorRole}` for application");
            var ir = await rm.CreateAsync(new IdentityRole(administratorRole));
            if (ir.Succeeded)
            {
                //logger.LogDebug($"Created the role `{administratorRole}` successfully");
            }
            else
            {
                var exception = new ApplicationException($"Default role `{administratorRole}` cannot be created");
                //logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(ir));
                throw exception;
            }
        }

        private static async Task<ApplicationUser> CreateDefaultUser(UserManager<ApplicationUser> um, string email)
        {
            //logger.LogInformation($"Create default user with email `{email}` for application");
           

            var user = new ApplicationUser(email, "First", "Last", new DateTime(1970, 1, 1));

           
            var ir = await um.CreateAsync(user);
            if (ir.Succeeded)
            {
                //logger.LogDebug($"Created default user `{email}` successfully");
            }
            else
            {
                var exception = new ApplicationException($"Default user `{email}` cannot be created");
                //logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(ir));
                throw exception;
            }

            var createdUser = await um.FindByEmailAsync(email);
            return createdUser;
        }

        private static async Task SetPasswordForDefaultUser(UserManager<ApplicationUser> um, string email, ApplicationUser user)
        {
            //logger.LogInformation($"Set password for default user `{email}`");
            const string password = "YourPassword01!";
            var ir = await um.AddPasswordAsync(user, password);
            if (ir.Succeeded)
            {
                //logger.LogTrace($"Set password `{password}` for default user `{email}` successfully");
            }
            else
            {
                var exception = new ApplicationException($"Password for the user `{email}` cannot be set");
                //logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(ir));
                throw exception;
            }
        }

        private static async Task AddDefaultRoleToDefaultUser(UserManager<ApplicationUser> um, string email, string administratorRole, ApplicationUser user)
        {
            //logger.LogInformation($"Add default user `{email}` to role '{administratorRole}'");
            var ir = await um.AddToRoleAsync(user, administratorRole);
            if (ir.Succeeded)
            {
                //logger.LogDebug($"Added the role '{administratorRole}' to default user `{email}` successfully");
            }
            else
            {
                var exception = new ApplicationException($"The role `{administratorRole}` cannot be set for the user `{email}`");
                //logger.LogError(exception, GetIdentiryErrorsInCommaSeperatedList(ir));
                throw exception;
            }
        }

        private static string GetIdentiryErrorsInCommaSeperatedList(IdentityResult ir)
        {
            string errors = null;
            foreach (var identityError in ir.Errors)
            {
                errors += identityError.Description;
                errors += ", ";
            }
            return errors;
        }
    }


Modify Program.cs
using Microsoft.Extensions.DependencyInjection;

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>>(); var dbInitializerLogger = services.GetRequiredService<ILogger<DbInitializer>>(); DbInitializer.Initialize(context, userManager, roleManager ).Wait(); //DbInitializer.Initialize(context); } catch (Exception ex) { } } host.Run(); }







留言

這個網誌中的熱門文章

Identity Server WebAPI