public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != todoListDto.TodoListId) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } TodoList todoList = todoListDto.ToEntity(); if (db.Entry(todoList).Entity.UserId != User.Identity.Name) { // Trying to modify a record that does not belong to the user return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } db.Entry(todoList).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.OK)); }
// PUT api/Todo/5 public HttpResponseMessage PutTodoItem(int id, TodoItemDto todoItemDto) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != todoItemDto.TodoItemId) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } TodoItem todoItem = todoItemDto.ToEntity(); TodoList todoList = db.TodoLists.Find(todoItem.TodoListId); if (todoList == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } if (todoList.UserId != User.Identity.Name) { // Trying to modify a record that does not belong to the user return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } // Need to detach to avoid duplicate primary key exception when SaveChanges is called db.Entry(todoList).State = EntityState.Detached; db.Entry(todoItem).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.NoContent)); }
// PUT api/Todo/5 public HttpResponseMessage PutTodoItem(int id, TodoItemDto todoItemDto) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } if (id != todoItemDto.TodoItemId) { return(Request.CreateResponse(HttpStatusCode.BadRequest)); } TodoItem todoItem = todoItemDto.ToEntity(); TodoList todoList = db.TodoLists.Find(todoItem.TodoListId); if (todoList == null) { return(Request.CreateResponse(HttpStatusCode.NotFound)); } if (todoList.UserId != User.Identity.Name) { // 사용자에게 속하지 않은 레코드를 수정하려고 시도합니다. return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } // SaveChanges가 호출될 때 중복 기본 키 예외 발생을 방지하려면 분리해야 합니다. db.Entry(todoList).State = EntityState.Detached; db.Entry(todoItem).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { return(Request.CreateResponse(HttpStatusCode.InternalServerError)); } return(Request.CreateResponse(HttpStatusCode.OK)); }