asp.net - 从 HttpModule 中的数据库获取角色
问题描述
我必须根据我的应用程序性质从数据库中获取用户的角色。我在context.AcquireRequestState += context_AcquireRequestState;
事件处理程序中对用户进行身份验证HttpModule
。我可以进行 db 调用HttpModule
以在 Identity 中分配角色吗?这是好习惯吗?如果没有,在调用控制器的操作方法之前我必须在哪里做。?
解决方案
我不知道您对 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();
}
来源在这里阅读
推荐阅读
- calllog - 如何按用户关联 RingCentral 通话数据和 Glip 发布数据?
- python - Python - 如何将while循环中的值存储到熊猫数据框中?
- android - RecyclerView 项目 ConstraintLayout 在使用 GridLayoutManager 时搞砸了
- java - Spring boot 测试:在嵌套测试中运行脚本 (@Sql("/script.sql"))
- dart - 您使用什么小部件来返回多个 int 类型?
- python - 如何使用python在for循环中加密图像
- c# - ASP.NET Core 2.1 文件上传 DirectoryNotFoundException:找不到路径的一部分
- email - 在 GO 中使用代理后面的 SMTP / 电子邮件客户端
- java - 工具栏后退按钮和 onBackPressed 方法的区别
- node.js - Nodejs:启用流式传输时,Morgon 日志未记录完整的响应时间