Manually initialize Asp.Net Identity tables?

倖福魔咒の 提交于 2019-12-11 23:56:24

问题


I created a website and published it to Azure. Now I want to protect some pages with authentication so I added the following code in the method Seed of Migrations.Configuration and published it to Azure.

However, the code is run even on local. The table AspNetRoles is still empty on both local and Azure SQL server. I tried to use Update-Database -Script -SourceMigration:0 to generate all the SQL statements but there is no SQL inserting the initial data to these tables of Asp.Net identity.

// Create role
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string roleName = "CanEdit";

var role = roleManager.FindByName(roleName);
if (role == null)
{
    role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(roleName);
    var roleresult = roleManager.Create(role);
}

var memberEmails = Properties.Settings.Default.CanEditMembers.Split(';');
foreach (var email in memberEmails)
{
    var user = userManager.FindByName(email.Trim());
    if (user != null)
    {
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }
}

Basically I want to insert 'CanEdit' to the AspNetRoles (I guess) and insert some other values (Users and their associations with the role) to these AspNetUser.... tables. Some of my Controls are already decorated with attribute [Authorize(Roles = "CanEdit")].

来源:https://stackoverflow.com/questions/31869823/manually-initialize-asp-net-identity-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!