สร้างโปรเจ็กส์แบบ WebApi (ด้วย Visual Studio 2017)
เพิ่มโมเดล ApplicationUser และ Seed ข้อมูลให้กับโปรเจ็กส์ WebApi
จากนั้นมาปรับแต่งค่าตามนี้
Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using WebApi.Data; using WebApi.Data.Models; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ApplicationDbContext"))); // Add ASP.NET Identity support services.AddIdentity<ApplicationUser, IdentityRole>( opts => { opts.Password.RequireDigit = true; opts.Password.RequireLowercase = true; opts.Password.RequireUppercase = true; opts.Password.RequireNonAlphanumeric = false; opts.Password.RequiredLength = 7; }) .AddEntityFrameworkStores<ApplicationDbContext>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); } } } |
ApplicationUser.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.AspNetCore.Identity; using System; using System.ComponentModel.DataAnnotations; namespace WebApi.Data.Models { public class ApplicationUser : IdentityUser { public ApplicationUser() { } //[Key] //[Required] //public string Id { get; set; } //[Required] //[MaxLength(128)] //public string UserName { get; set; } //[Required] //public string Email { get; set; } public string DisplayName { get; set; } public string Notes { get; set; } [Required] public int Type { get; set; } [Required] public int Flags { get; set; } [Required] public DateTime CreatedDate { get; set; } [Required] public DateTime LastModifiedDate { get; set; } } } |
บรรทัดที่ 7 : ให้ ApplicationUser
สืบทอดมาจาก IdentityUser
(เดิมไม่ได้สืบทอด)
ApplicationDbContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using WebApi.Data.Models; namespace WebApi.Data { //public class ApplicationDbContext : DbContext public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } //public DbSet<Models.ApplicationUser> Users { get; set; } } } |
บรรทัดที่ 8 : ให้ ApplicationDbContext
สืบทอดมาจาก IdentityDbContext
(เดิมสืบทอดมาจาก DbContext)
SeedData.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using System; using System.Linq; using System.Threading.Tasks; using WebApi.Data.Models; namespace WebApi.Data { public static class SeedData { public static void Initialize(IServiceProvider serviceProvider) { using (var context = new ApplicationDbContext( serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>())) { var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); // Create default Users (if there are none) if (!context.Users.Any()) CreateUsers(context, roleManager, userManager).GetAwaiter().GetResult(); ; } } private static async Task CreateUsers(ApplicationDbContext context, RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager) { // local variables DateTime createdDate = new DateTime(2016, 03, 01, 12, 30, 00); DateTime lastModifiedDate = DateTime.Now; string role_Administrator = "Administrator"; string role_RegisteredUser = "RegisteredUser"; //Create Roles (if they doesn't exist yet) if (!await roleManager.RoleExistsAsync(role_Administrator)) { await roleManager.CreateAsync(new IdentityRole(role_Administrator)); } if (!await roleManager.RoleExistsAsync(role_RegisteredUser)) { await roleManager.CreateAsync(new IdentityRole(role_RegisteredUser)); } // Create the "Admin" ApplicationUser account (if it doesn't exist already) var userAdmin = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Admin", Email = "admin@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert "Admin" into the Database and assign the "Administrator" and "RegisteredUser" roles to him. if (await userManager.FindByNameAsync(userAdmin.UserName) == null) { await userManager.CreateAsync(userAdmin, "Pass4Admin"); await userManager.AddToRoleAsync(userAdmin, role_RegisteredUser); await userManager.AddToRoleAsync(userAdmin, role_Administrator); // Remove Lockout and E-Mail confirmation. userAdmin.EmailConfirmed = true; userAdmin.LockoutEnabled = false; } #if DEBUG // Create some sample registered user accounts (if they don't exist already) var userJack = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Jack", Email = "mr.phaisarn@gmail.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Solice = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Solice", Email = "solice@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; var user_Vodan = new ApplicationUser() { SecurityStamp = Guid.NewGuid().ToString(), UserName = "Vodan", Email = "vodan@testmakerfree.com", CreatedDate = createdDate, LastModifiedDate = lastModifiedDate }; // Insert sample registered users into the Database and also assign the "Registered" role to him. if (await userManager.FindByNameAsync(userJack.UserName) == null) { await userManager.CreateAsync(userJack, "Pass4Ryan"); await userManager.AddToRoleAsync(userJack, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. userJack.EmailConfirmed = true; userJack.LockoutEnabled = false; } if (await userManager.FindByNameAsync(user_Solice.UserName) == null) { await userManager.CreateAsync(user_Solice, "Pass4Solice"); await userManager.AddToRoleAsync(user_Solice, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. user_Solice.EmailConfirmed = true; user_Solice.LockoutEnabled = false; } if (await userManager.FindByNameAsync(user_Vodan.UserName) == null) { await userManager.CreateAsync(user_Vodan, "Pass4Vodan"); await userManager.AddToRoleAsync(user_Vodan, role_RegisteredUser); // Remove Lockout and E-Mail confirmation. user_Vodan.EmailConfirmed = true; user_Vodan.LockoutEnabled = false; } #endif await context.SaveChangesAsync(); } } } |
บรรทัดที่ 18-19 : ใช้ RoleManager
และ UserManager
Perform initial migration
[code]
> dotnet ef migrations add "Identity" -o "Data\Migrations"
> dotnet ef database update
[/code]
แต่ถ้าจะลบ Database แล้วสร้าง Database ขึ้นใหม่
ให้ลบโฟลเดอร์ Migrations
แล้วใช้คำสั่ง
[code]
> dotnet ef database drop
> dotnet ef migrations add Initial
> dotnet ef database update
[/code]
รันกด F5
เสร็จแล้วกลับมาดูที่ Database จะมีข้อมูลเพิ่มเข้ามา (แต่หน้าเว็บยังไม่เห็นอะไร)