public IHttpActionResult PutUser(string userName, UserViewModel user_view_model) { if (!ModelState.IsValid) return BadRequest(ModelState); if (userName != user_view_model.UserName) return BadRequest(); //把資料庫中的那筆資料讀出來 var user_db = db.Users.Find(userName); if (user_db == null) { return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!")); } else { try { //移除舊角色功能選單 foreach (var item in user_db.Role.Menus) { user_db.Menus.Remove(item); } //更新新角色 user_db.Role_Id = user_view_model.RoleId; db.Entry(user_db).OriginalValues["Timestamp"] = Convert.FromBase64String(user_view_model.TimestampString); db.SaveChanges(); //加入新角色功能選單 var roleMenus = user_db.Role.Menus; foreach (var item in roleMenus) { user_db.Menus.Add(item); } db.SaveChanges(); //寫入AccessLog MPAccessLog.WriteEntry(User.Identity.Name, AccessAction.Update, "User", JsonConvert.SerializeObject(new { user_db.UserName, roleName=user_db.Role.Name })); } catch (DbUpdateConcurrencyException) { if (!UserExists(userName)) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, "這筆資料已被刪除!")); else throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Conflict, "這筆資料已被其他人修改!"));// "" } catch (Exception ex) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } } return Ok(ToUserViewModel(user_db)); }
public IHttpActionResult PostUser(UserViewModel user_view_model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var role = db.Roles.Find(user_view_model.RoleId); if (role==null) { return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, "沒有對應的角色!")); } User user = db.Users.Find(user_view_model.UserName); if (user == null) { try { //新增使用者 user = new User { UserName = user_view_model.UserName, Password = user_view_model.UserName, Role = role }; db.Users.Add(user); //新增使用者角色的功能選單 foreach (var menu in role.Menus) { user.Menus.Add(menu); } //寫入資料庫 db.SaveChanges(); //寫入AccessLog MPAccessLog.WriteEntry(User.Identity.Name, AccessAction.Create, "User", JsonConvert.SerializeObject(new { user.UserName, roleName=user.Role.Name })); } catch (Exception ex) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } } return CreatedAtRoute("GetUserByUserName", new { userName = user.UserName }, ToUserViewModel(user)); }