【问题标题】:How rename Asp.net Identity Role如何重命名 Asp.net 身份角色
【发布时间】:2016-03-30 19:37:46
【问题描述】:

我向数据库添加了 3 个角色。 "Admin""Moderator""User"。我只想重命名 "Admin""Administrator"。我使用此代码,但它的工作不正确。它返回错误{“数据库操作预计会影响 1 行,但实际上影响了 0 行。自从加载实体以来,数据可能已被修改或删除。有关理解和处理的信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=527962乐观并发异常。"}

Edit.cshtml

@model Microsoft.AspNet.Identity.EntityFramework.IdentityRole
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)
        <div>
            Role name
        </div>
        <p>
            @Html.TextBoxFor(model => model.Name)
        </p>
        <input type="submit" value="Save" />
    }

RoleController

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(IdentityRole role) //IdentityRole role
    {
        try
        {

            context.Entry(role).State = EntityState.Modified;
            context.SaveChanges();

            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            return View();
        }
    }

【问题讨论】:

    标签: asp.net roles asp.net-identity-3


    【解决方案1】:

    使用 Identity 提供的角色管理器。

    在 Startup.Auth 中,确保 RoleManager 是这样引用的:

    public void ConfigureAuth(IAppBuilder app)
    {
        // Add this reference
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    }
    

    确保您的 Controller 包含此构造函数:

    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }
    

    然后您可以使用它代替问题中的代码(以异步形式给出):

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(IdentityRole role)
    {
        try
        {
            IdentityRole thisRole = await RoleManager.FindByIdAsync(role.Id);
            thisRole.Name = role.Name;
            await RoleManager.UpdateAsync(thisRole);
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {
            return View();
        }
    }
    

    最后确保您像这样处理角色管理器:

    protected override void Dispose(bool disposing)
    {
        if (disposing && RoleManager != null)
        {
            RoleManager.Dispose();
            RoleManager = null;
        }
        if (disposing)
        {
            context.Dispose();
        }
        base.Dispose(disposing);
    }
    

    希望这能解决问题。

    【讨论】:

    • 我需要 Identity 3.0 的解决方案
    • 好的,但问题没有这么说,Identity 3 仍处于预发布阶段。这是用于身份和身份 2。
    【解决方案2】:

    这就是我的做法。我的管理页面的这一部分,选项:“添加/编辑角色”

      [HttpPut]
        public string UpdateRole(RoleModel roleModel)
        {
            string success = "";
            using (var context = new ApplicationDbContext())
            {
                var roleStore = new RoleStore<IdentityRole>(context);
                var storeManager = new RoleManager<IdentityRole>(roleStore);
                IdentityRole thisRole = roleStore.Roles.Where(r => r.Id == roleModel.Id).FirstOrDefault();
                if (thisRole != null)
                {
                    thisRole.Name = roleModel.Name;
                    IdentityResult result = storeManager.Update(thisRole);
                    if(result.Succeeded)
                    success = "ok";
                    else
                    {
                        success = "ERROR";
                        foreach (string error in result.Errors)
                        {
                            success += " :" + error;
                        }
                    }
                }
            }
            return success;
        }
    

    你必须使用一个特殊的 RoleManager,我称之为 storeManager,它内置在 ApplicationDbContext 的 using 块中,以返回所有角色的列表。然后我使用 linq where 子句来查找我想要的角色。然后,您通过更改角色名称来修改角色并调用 .Update,它也由 roleStore StoreManager 对象公开。 尝试直接编辑 AspNet 用户文件可以在 EntityFramework 中完成,除了在 SQL 中完成之外,没有任何效果。

    【讨论】:

      猜你喜欢
      • 2016-09-05
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-06-07
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      相关资源
      最近更新 更多