コード例 #1
0
        public void PostComment_WhenModelValid_ShouldSaveToDatabase()
        {
            var testUser = this.RegisterTestUser();

            var testComment = new CommentModel()
            {
                Text = "Wow cool story bro!",
            };

            string sessionKey = testUser.SessionKey;

            int testPostId = this.PostATestPost(sessionKey);

            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = sessionKey;

            var response = this.httpServer.Put(string.Format("api/posts/{0}/comment", testPostId), testComment, headers);

            Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
        }
コード例 #2
0
        public void PostComment_WhenModelInvalid_CommentTextIsTooShort()
        {
            var testUser = this.RegisterTestUser();

            var testComment = new CommentModel()
            {
                Text = "Cool.",
            };

            string sessionKey = testUser.SessionKey;

            int testPostId = this.PostATestPost(sessionKey);

            var headers = new Dictionary<string, string>();
            headers["X-sessionKey"] = sessionKey;

            var response = this.httpServer.Put(string.Format("api/posts/{0}/comment", testPostId), testComment, headers);

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
        }
コード例 #3
0
        public HttpResponseMessage PostComment(int postId, CommentModel model, string sessionKey)
        {
            var context = new BloggingSystemContext();
            var post = context.Posts.FirstOrDefault(p => p.PostId == postId);

            try
            {
                this.VerifySessionKey(sessionKey);

                if (post == null)
                {
                    throw new ArgumentOutOfRangeException("Post not found");
                }

                if (string.IsNullOrEmpty(model.Text))
                {
                    throw new ArgumentNullException("Comment text is mandatory");
                }
            }
            catch (Exception e)
            {
                var errorResponse = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
                return errorResponse;
            }

            var user = context.Users.FirstOrDefault(
                usr => usr.SessionKey == sessionKey);

            var comment = new Comment()
            {
                Text = model.Text,
                PostDate = DateTime.Now,
                User = user,
                Post = post
            };

            context.Comments.Add(comment);
            context.SaveChanges();

            var response = this.Request.CreateResponse(HttpStatusCode.Created);

            return response;
        }