使用用户管理器之用户管理
一、建立模型
1、在Models文件夹上点右键 》添加》类 类的名称自定,我用AdminViewModels命名的。
2、更改模板自建的AdminViewModels类为RoleViewModel,并添加EditUserViewModel类,代码完成如下:
public class RoleViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "角色名称")]
public string Name { get; set; }
} public class EditUserViewModel
{
public string Id { get; set; } //[Required(AllowEmptyStrings = false)]
//[Display(Name = "电邮地址")]
//[EmailAddress]
//public string Email { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "用户名称")]
public string UserName { get; set; } public IEnumerable<SelectListItem> RolesList { get; set; }
}
为保证代码简洁,删除不必要的using。
二、建立控制器UsersAdminController
1、在controllers文件夹上点右键》添加》控制器, 我这里选的是“MVC5 控制器-空”,名称设置为:UsersAdminController.cs
2、添加操作权限。在空间命名下第一个{下面(9行)添加[Authorize(Roles = "Admin")]用以此控制器操作只有admin角色组有权限访问。如果你选择了之前的可选操作这里可以直接添加权限,否则要么改,要么先注释掉。
3、在public class UsersAdminController : Controller内添加如下代码:
public UsersAdminController()
{
} public UsersAdminController(ApplicationUserManager userManager, ApplicationRoleManager roleManager)
{
UserManager = userManager;
RoleManager = roleManager;
} private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
} private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
}
private set
{
_roleManager = value;
}
}
添加完代码后,记得根据错误提示添加命名空间using xxx;
4、修改ActionResult Index()。将其改为异步调用,并显示用户列表。代码如下:
//
// GET: /Users/异步获取用户列表
public async Task<ActionResult> Index()
{
return View(await UserManager.Users.ToListAsync());
}
5、添加用户详情操作
// GET: /Users/Details/5/经由ID编号异步获取用户详细信息
public async Task<ActionResult> Details(string id)
{
//用户为空时返回400错误
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
} //按Id查找用户
var user = await UserManager.FindByIdAsync(id);
ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
return View(user);
}
6、添加创建用户操作
//
//异步读取用户创建
// GET: /Users/Create
public async Task<ActionResult> Create()
{
//读取角色列表
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
} //
//异步写入用户创建
// POST: /Users/Create
[HttpPost]
public async Task<ActionResult> Create(RegisterViewModel userViewModel, params string[] selectedRoles)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = userViewModel.Email, Email = userViewModel.Email };
var adminresult = await UserManager.CreateAsync(user, userViewModel.Password); //将用户添加到选定角色
if (adminresult.Succeeded)
{
if (selectedRoles != null)
{
var result = await UserManager.AddToRolesAsync(user.Id, selectedRoles);
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");
return View();
}
}
}
else
{
ModelState.AddModelError("", adminresult.Errors.First());
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View(); }
return RedirectToAction("Index");
}
ViewBag.RoleId = new SelectList(RoleManager.Roles, "Name", "Name");
return View();
}
7、添加用户编辑操作
//
//异步读取用户编辑
// GET: /Users/Edit/1
public async Task<ActionResult> Edit(string id)
{
//ID为空返回错误提示
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
} //查找用户
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
//查找角色
var userRoles = await UserManager.GetRolesAsync(user.Id); return View(new EditUserViewModel()
{
Id = user.Id,
UserName = user.UserName,
RolesList = RoleManager.Roles.ToList().Select(x => new SelectListItem()
{
Selected = userRoles.Contains(x.Name),
Text = x.Name,
Value = x.Name
})
});
} //
//异步写入用户编辑
// POST: /Users/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "UserName,Id")] EditUserViewModel editUser, params string[] selectedRole)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByIdAsync(editUser.Id);
if (user == null)
{
return HttpNotFound();
} user.UserName = editUser.UserName;
//user.Email = editUser.Email; var userRoles = await UserManager.GetRolesAsync(user.Id); selectedRole = selectedRole ?? new string[] { }; //将用户添加到指定的角色
var result = await UserManager.AddToRolesAsync(user.Id, selectedRole.Except(userRoles).ToArray<string>()); if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
} //将用户从指定的角色中删除
result = await UserManager.RemoveFromRolesAsync(user.Id, userRoles.Except(selectedRole).ToArray<string>()); if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
ModelState.AddModelError("", "编辑操作失败。");
return View();
}
[ValidateAntiForgeryToken]为加密操作。
8、添加用户删除操作
//
//异步读取用户删除
// GET: /Users/Delete/5
public async Task<ActionResult> Delete(string id)
{
//ID为空返回错误提示
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
} //
//异步写入用户删除
// POST: /Users/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(string id)
{
if (ModelState.IsValid)
{
//ID为空返回错误提示
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
} var user = await UserManager.FindByIdAsync(id);
if (user == null)
{
return HttpNotFound();
}
var result = await UserManager.DeleteAsync(user);
if (!result.Succeeded)
{
ModelState.AddModelError("", result.Errors.First());
return View();
}
return RedirectToAction("Index");
}
return View();
}
用户管理的控制器编写结束。