【发布时间】:2018-03-26 17:40:21
【问题描述】:
当我想获取当前用户角色名称,当我想编辑用户配置文件时,为什么我在 Asp.Net Mvc 代码中的操作会崩溃? 这段代码崩溃了
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id;
我得到的错误信息是:500(内部服务器错误)
这是我的编辑用户视图
public class EditUserViewModel
{
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public List<SelectListItem> ApplicationRoles { get; set; }
public string ApplicationRoleId { get; set; }
public List<SelectListItem> DepartmentNames { get; set; }
public int DeptId { get; set; } // I have DeptId too in my AspNetUser table
}
还有我的 Edituser 操作
[HttpGet]
public async Task<IActionResult> EditUser(string id)
{
EditUserViewModel model = new EditUserViewModel();
model.ApplicationRoles = roleManager.Roles.Select(r => new SelectListItem
{
Text = r.Name,
Value = r.Id
}).ToList();
model.DepartmentNames = context.Departments.Select(s => new SelectListItem
{
Text = s.DeptName,
Value = s.DeptId.ToString()
}).ToList();
if (!String.IsNullOrEmpty(id))
{
ApplicationUser user = await userManager.FindByIdAsync(id);
if (user != null)
{
model.Name = user.Name;
model.Email = user.Email;
model.DeptId = user.DepartmentId;
//model.ApplicationRoleId crashing
model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id; // Here crashing .. I don't know why.. Server 500 error
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Id", "Name", model.ApplicationRoleId);
ViewBag.DeptId = new SelectList(db.Departments, "Deptd", "DeptName", model.DeptId);
}
}
return PartialView("_EditUser", model);
}
我试过这样,但即使是这个崩溃..
string existingRole = UserManager.GetRolesAsync(user.Id).Result.Single();// This crashing
然后放在这里:
string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id;
但是字符串existingRole 对我不起作用..
如有任何帮助,我将不胜感激。
【问题讨论】:
-
您不应该使用
Result调用异步方法。等待你的方法,如var r=await UserManager.GetRolesAsync(user.Id); var existingRole=u.First();当你确定你的集合总是只有一个项目时,也使用 Single 方法,否则它会抛出一个InvalidOperationException异常。 -
@Shyju 谢谢你的回复,但你是什么意思 var r=await UserManager.GetRolesAsync(user.Id);?把这个结果放在哪里?你的意思是model.ApplicationRoleId = wait UserManager.GetRolesAsync(user.Id);?然后 var existingRole=u.First() ?你要去哪里?你必须在某处声明......我的意思是我应该初始化我的model.ApplicationRoleId什么? .再次感谢您。
-
@Shyju ,你能帮忙吗..?