Heidi T.
Heidi T.

Reputation: 75

ASP.NET Identity Adding Role

im working on a project with MVC. I want to use IDENTITY Library for membership. This is solution view:

I made accountController and add Registerview.:

    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (!ModelState.IsValid) return View(model);

        var userManager = MemberShipTools.NewUserManager();

        var roleManager = MemberShipTools.NewRoleManager();
        var checkUser = userManager.FindByName(model.TCNo);



        if (checkUser!=null)
        {
            ModelState.AddModelError(string.Empty, "Bu TC No sistemde kayıtlı");
            return View(model);
        }

        checkUser = userManager.FindByEmail(model.Email);
        if (checkUser!=null)
        {
            ModelState.AddModelError(string.Empty, "Bu mail adresi sistemde kayıtlı");
            return View(model);
        }

        var user = new Kullanici()
        {
            Ad=model.Ad,
            Soyad=model.Soyad,
            Email=model.Email,
            UserName=model.TCNo,        
        };

        var response = userManager.Create(user, model.Sifre);

        if (response.Succeeded)
        {
            if (userManager.Users.ToList().Count() == 1)
            {
                userManager.AddToRole(user.Id, "Admin");
            }
            else
            {
                userManager.AddToRole(user.Id, "Passive");
            }
            return RedirectToAction("Login", "Hesap");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Kayıt işleminde bir hata oluiştu");
            return View(model);
        }
    }

when i try to add new member it says "Role Admin does not exist." but added new member to User Table, AspNet Role Table was empty. After that i search and found a solving in this site, i add this lines to my code and it works great.

         const string roleName = "Admin";

        var role = roleManager.FindByName(roleName);
        if (role == null)
        {
            role = new Rol() { Name="Admin", Aciklama="Site Yöneticisi"};
            roleManager.Create(role);
        }

But its not logical, every register page i check roles and try to add role, my question is Where I should to write this Roll Adding codes, which layer which page, because i need only two or three roles. I must to create them one time , i know that but i dont know where I shoul to do this. Thanks for answers sorry for my bad english :)

Upvotes: 0

Views: 1587

Answers (1)

Caz1224
Caz1224

Reputation: 1569

Something that might help is having a seed database class that runs at start up. Is it safe to assume you are using a code first database? I will show examples for both.

So first thing to do in your "Data" folder is create a class called "SeedData"

using Project.Models.DatabaseModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Project.Data
{
    public class SeedData
    {
        private ApplicationDbContext _context;

        public ApplicationContextSeedData(ApplicationDbContext context)
        {
            _context = context;
        }
        public void EnsureSeedData()
        {

            if ("Check if roles are already there")
            {
                role = new Rol() { Name="Role1", Aciklama="Site Yöneticisi"};
                roleManager.Create(role);
                role = new Rol() { Name="Role2", Aciklama="Site Yöneticisi"};
                roleManager.Create(role);
                role = new Rol() { Name="Role3", Aciklama="Site Yöneticisi"};
                roleManager.Create(role);

            }

        }

    }
}

Then once you have that made in your Startup.cs class I add the following line:

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDbContext<ApplicationDbContext>(options =>
           options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
        services.AddScoped<SeedData>(); <------ This Line

    }

Then once you have that, anything you want to make sure is created in your database at the point your application starts will go into your SeedData class.

Upvotes: 1

Related Questions