asp.net identity 2.2.0 在WebForm下的角色启用和基本使用(一)

基本环境:asp.net 4.5.2 

仔细看了在Webform下,模板就已经启动了角色控制,已经不用再进行设置了。直接调用相关类就可以了。这和原来在网站根目录下配置Web.config完全不同了。 

相关角色控制如下

添加角色:

web窗体代码: 

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="RolesAdmin.aspx.cs" Inherits="ttg2015.Admin.RolesAdmin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <div>
        <div>
            <h2>角色创建
            </h2>
            <div>
                <p>
                    角色创建
                </p>
                <div>
                    角色名称:<asp:TextBox ID="TextBoxRoleName" runat="server"></asp:TextBox>
                    <asp:Button ID="ButtonRolechuangjian" runat="server" Text="创建角色" OnClick="ButtonRolechuangjian_Click" />
                    <br />
                    <asp:Label ID="Labelcjts" runat="server"></asp:Label>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="TextBoxRoleName" CssClass="text-warning" ErrorMessage="RequiredFieldValidator">您未输入需创建的角色名称。</asp:RequiredFieldValidator>
                </div>
            </div>
</div>
    </div>
</asp:Content>

.cs文件代码

public partial class RolesAdmin : System.Web.UI.Page
    {
        Models.ApplicationDbContext context = new ApplicationDbContext();       

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void ButtonRolechuangjian_Click(object sender, EventArgs e)
        {
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);            
                if (!roleManager.RoleExists(TextBoxRoleName.Text))
                {
                  var  IdRoleResult = roleManager.Create(new IdentityRole { Name = TextBoxRoleName.Text });
                    Labelcjts.Text = "角色已经创建完成";                    
                }
                else
                {
                    Labelcjts.Text = "该角色已存在,无需创建。";
                }
        }
}

所需的空间引用自行添加下。

可选操作(未做测试有时间尽快测试):

这个可选操作用于在创建网站的时候,像网站数据库中添加一个管理用户。如果直接发布给别人用的话 还是挺不错的,自己用的话可以省略掉。

第一步:在identityconfig.cs可以配置添加一个用户(用户名为:“admin@123.com”,密码为“Admin@123456”)并把该用户添加到角色("Admin")中。

代码如下:

public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {

        internal void InitializeIdentityForEF()
        {
            Models.ApplicationDbContext context = new ApplicationDbContext();
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

            const string name = "admin@123.com";//用户名
            const string password = "Admin@123456";//密码
            const string roleName = "Admin";//用户要添加到的角色组

            //如果没有Admin用户组则创建该组
            if (!roleManager.RoleExists(roleName))
            {
                var IdRoleResult = roleManager.Create(new IdentityRole { Name = roleName });
            }
           //如果没有admin@123.com用户则创建该用户
           var appUser = new ApplicationUser {UserName = name, Email = name };
           var IdUserResult = userManager.Create(appUser, password);

            // 把用户admin@123.com添加到用户组Admin中
           if (!userManager.IsInRole(userManager.FindByEmail(name).Id, roleName))
            {
                IdUserResult = userManager.AddToRole(userManager.FindByEmail(name).Id, roleName);
            }
        }
    }

  

第二步:修改项目目录下的Global.asax.cs文件。          

            在void Application_Start(object sender, EventArgs e)   类方法中添加如下代码

// 在第一次启动网站时初始化数据库添加管理员用户凭据和admin 角色到数据库
            Database.SetInitializer(new ApplicationDbInitializer());
            ApplicationDbInitializer neizhi = new ApplicationDbInitializer();
            neizhi.InitializeIdentityForEF();

这两步再添加的过程中要记得在各自的文件内添加对用的引用空间。

温馨提示:

可选操作可以改良下,把第一步独立出来作为一个类,步骤:你新建个目录》添加一个“网站初始化”类》添加一个“初始化方法”,把第一步里的代码复制进去,保存。再对应修改Global.asax.cs文件的最后两句,也能完成该功能。

个人觉得改良方法比较好。

原文地址:https://www.cnblogs.com/chonghanyu/p/4101517.html