コード例 #1
0
        // DELETE api/TodoList/5
        public HttpResponseMessage DeleteTodoList(int id)
        {
            TodoList todoList = db.TodoLists.Find(id);
            if (todoList == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            if (db.Entry(todoList).Entity.UserId != User.Identity.Name)
            {
                // Trying to delete a record that does not belong to the user
                return Request.CreateResponse(HttpStatusCode.Unauthorized);
            }

            TodoListDto todoListDto = new TodoListDto(todoList);
            db.TodoLists.Remove(todoList);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.InternalServerError);
            }

            return Request.CreateResponse(HttpStatusCode.OK, todoListDto);
        }
コード例 #2
0
        // POST api/TodoList
        public HttpResponseMessage PostTodoList(TodoListDto todoListDto)
        {
            if (ModelState.IsValid)
            {
                todoListDto.UserId = User.Identity.Name;
                TodoList todoList = todoListDto.ToEntity();
                db.TodoLists.Add(todoList);
                db.SaveChanges();
                todoListDto.TodoListId = todoList.TodoListId;

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, todoListDto);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = todoListDto.TodoListId }));
                return response;
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }
コード例 #3
0
        // PUT api/TodoList/5
        public HttpResponseMessage PutTodoList(int id, TodoListDto todoListDto)
        {
            if (ModelState.IsValid && id == todoListDto.TodoListId)
            {
                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);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }
        }