2017-10-14 121 views
0

为什么我的Action在Asp.Net Mvc代码崩溃时想获取当前用户角色名称,当我想编辑用户配置文件? 此代码崩溃Asp.Net Mvc编辑用户配置文件与用户角色

model.ApplicationRoleId = roleManager.Roles.Single(r => r.Name == userManager.GetRolesAsync(user).Result.Single()).Id; 

错误消息我得到的是:500(内部服务器错误)

这里是我的EditUserview

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并没有为我工作..

我会greateful任何帮助..

+0

您不应该使用Result来调用异步方法。等待你的方法,如'var r = await UserManager.GetRolesAsync(user.Id); var existingRole = u.First();'当你确定你的集合总是只有一个项目时,也使用Single方法,否则会抛出'InvalidOperationException'异常。 – Shyju

+0

@Shyju谢谢你的回应,但你是什么意思var r = await UserManager.GetRolesAsync(user.Id);?在哪里放置这个结果?你的意思是model.ApplicationRoleId =等待UserManager.GetRolesAsync(user.Id);?然后var existingRole = u.First()?你来了哪里?你必须在某处申报......我的意思是我应该初始化我的模型.ApplicationRoleId? 。再次感谢你。 –

+0

@Shyju,请你帮忙..? –

回答

0

我不喜欢这作为@Shyju写道

var role = await UserManager.GetRolesAsync(user.Id); 
         var existingRole = role.First(); 
    if (existingRole != null) 
     { 
    string existingRoleId = RoleManager.Roles.Single(r => r.Name == existingRole).Id; 
    model.ApplicationRoleId = existingRoleId; 
    ..... and so on .... 

    } 

谢谢哟u @Shyju