AspNetUsers tablosuna Admin, Teacher ve Student kullanıcılarını ekleyelim. Böylece tanımladığımız rollere ait kullanıcıları oluşturmuş olacağız.
Data klasörü altında SeedData dosyası oluşturalım. Bu dosya aracılığıyla AspNetUsers tablosuna kayıtları eklemiş olacağız.
using Microsoft.AspNetCore.Identity;
using SchoolManagement.Models;
namespace SchoolManagement.Data
{
public static class SeedData
{
public static async Task Initialize(IServiceProvider serviceProvider)
{
using (var scope = serviceProvider.CreateScope())
{
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roleNames = { "Admin", "Teacher", "Student" };
foreach (var roleName in roleNames)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
await AddUserIfNotExists(userManager, "admin@admin.com", "Admin123!", "Admin Kullanıcı", "Admin");
await AddUserIfNotExists(userManager, "teacher@school.com", "Teacher123!", "Öğretmen Kullanıcı", "Teacher");
await AddUserIfNotExists(userManager, "student@school.com", "Student123!", "Öğrenci Kullanıcı", "Student");
}
}
private static async Task AddUserIfNotExists(UserManager<ApplicationUser> userManager, string email, string password, string fullName, string role)
{
var user = await userManager.FindByEmailAsync(email);
if (user == null)
{
user = new ApplicationUser
{
UserName = email.Split('@')[0], // Kullanıcı adı e-posta öncesi kısım
Email = email,
EmailConfirmed = true,
FullName = fullName
};
var result = await userManager.CreateAsync(user, password);
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, role);
}
}
}
}
}
Program.cs içinde SeedData'yı Çağıralım. Program.cs dosyasında app.Run(); satırından önce aşağıdaki kodu ekleleyim.
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SchoolManagement.Data;
using SchoolManagement.Models;
var builder = WebApplication.CreateBuilder(args);
// Veritabanı bağlantısını ekle
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Kimlik doğrulama servisini ekle
builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Hata sayfası ve yönlendirmeler
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
// Kimlik doğrulama ve yetkilendirme işlemleri
app.UseAuthentication(); // Kimlik doğrulama işlemi
app.UseAuthorization(); // Yetkilendirme işlemi
// Eğer kullanıcı yetkisi olmayan bir sayfaya gitmeye çalışırsa, yönlendirilecek sayfa
app.UseStatusCodePagesWithRedirects("/Account/AccessDenied");
// Statik dosyalar ve dosya yönlendirme işlemleri
app.UseDefaultFiles(); // Default dosya yönlendirmesi (index.html vs.)
app.UseStaticFiles(); // Statik dosyaları (CSS, JS, resimler) kullanabilmesi için
// Routing işlemi
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
await SeedData.Initialize(services);
}
app.Run();
Uygulamayı Çalıştıralım ve tabloya kayıtların eklenip eklenmediğini kontrol edelim.