首页 > 解决方案 > 从 HttpModule 中的数据库获取角色

问题描述

我必须根据我的应用程序性质从数据库中获取用户的角色。我在context.AcquireRequestState += context_AcquireRequestState;事件处理程序中对用户进行身份验证HttpModule。我可以进行 db 调用HttpModule以在 Identity 中分配角色吗?这是好习惯吗?如果没有,在调用控制器的操作方法之前我必须在哪里做。?

标签: asp.netasp.net-mvcasp.net-web-apiasp.net-web-api2httpmodule

解决方案


我不知道您对 Aquaire 请求状态做了什么,理想情况下您必须执行以下操作:

[Authorize(Roles="Admin")]
[Route("user/{id:guid}/roles")]
[HttpPut]
public async Task<IHttpActionResult> AssignRolesToUser([FromUri] string id, [FromBody] string[] rolesToAssign)
{

    var appUser = await this.AppUserManager.FindByIdAsync(id);

    if (appUser == null)
    {
        return NotFound();
    }

    var currentRoles = await this.AppUserManager.GetRolesAsync(appUser.Id);

    var rolesNotExists = rolesToAssign.Except(this.AppRoleManager.Roles.Select(x => x.Name)).ToArray();

    if (rolesNotExists.Count() > 0) {

        ModelState.AddModelError("", string.Format("Roles '{0}' does not exixts in the system", string.Join(",", rolesNotExists)));
        return BadRequest(ModelState);
    }

    IdentityResult removeResult = await this.AppUserManager.RemoveFromRolesAsync(appUser.Id, currentRoles.ToArray());

    if (!removeResult.Succeeded)
    {
        ModelState.AddModelError("", "Failed to remove user roles");
        return BadRequest(ModelState);
    }

    IdentityResult addResult = await this.AppUserManager.AddToRolesAsync(appUser.Id, rolesToAssign);

    if (!addResult.Succeeded)
    {
        ModelState.AddModelError("", "Failed to add user roles");
        return BadRequest(ModelState);
    }

    return Ok();
}

来源在这里阅读


推荐阅读