예제 #1
0
        public IHttpActionResult PutUser(int id, UserModel user)
        {
            // Allow only for authorized user
            var userToCheck = _userRepository.FirstOrDefault(u => u.UserName == User.Identity.Name);
            if (!userToCheck.Authorized)
            {
                return Unauthorized();
            }

            // Validate the request
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != user.Id)
            {
                return BadRequest();
            }

            // Get the DB user, update it according to the input UserModel object,
            //   and then update the DB user in the database
            var dbUser = _userRepository.GetByID(id);
            if (dbUser == null)
            {
                return NotFound();
            }
            dbUser.Update(user);
            _userRepository.Update(dbUser);

            // Save database changes
            try
            {
                _unitOfWork.Commit();
            }
            catch (DBConcurrencyException e)
            {
                if (!UserExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw new Exception("Unable to update the user in the database", e);
                }
            }
            return StatusCode(HttpStatusCode.NoContent);
        }
예제 #2
0
        public IHttpActionResult PostUser(UserModel user)
        {
            // Validate request
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            //Set up new User object, populated from input user
            User dbUser = new User();
            dbUser.Update(user);

            // Add the new User object to the DB
            _userRepository.Add(dbUser);

            // Save the changes in the database
            try
            {
                _unitOfWork.Commit();
            }
            catch (Exception e)
            {
                throw new Exception("Unable to add the user to the database", e);
            }

            // Set user ID in UserModel object with the ID
            //  that was set in the DB user after db.SaveChanges
            user.Id = dbUser.Id;
            return CreatedAtRoute("DefaultApi", new { id = user.Id }, user);
        }