// 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));
        }
Exemplo n.º 2
0
        // 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));
        }