public HttpResponseMessage PostCreatePost( [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey , [FromBody]CreatePostModel postToAdd) { var responseMsg = this.PerformOperationAndHandleExceptions( () => { var context = new BlogDb(); using (context) { UserPersister.ValidateSessionKey(sessionKey); var user = context.Users.FirstOrDefault( usr => usr.SessionKey == sessionKey); if (user == null) { throw new InvalidOperationException("Invalid username or password"); } List<Tag> tags = new List<Tag>(); var wordsFromTitle = postToAdd.Title.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < wordsFromTitle.Length; i++) { tags.Add(new Tag() { TagName = wordsFromTitle[i].ToLower() }); } for (int i = 0; i < postToAdd.Tags.Length; i++) { tags.Add(new Tag() { TagName = postToAdd.Tags[i].ToLower() }); } var post = new Post() { Title = postToAdd.Title, DateCreated = DateTime.Now, UserOfPost = user, Text = postToAdd.Text, Tags = tags }; context.Posts.Add(post); context.SaveChanges(); CreatedPostModel postModel = new CreatedPostModel() { Id = post.PostId, Title = post.Title }; var response = this.Request.CreateResponse(HttpStatusCode.Created, postModel); return response; } }); return responseMsg; }
public HttpResponseMessage PostPost(CreatePostModel model, [ValueProvider(typeof(HeaderValueProviderFactory<string>))] string sessionKey) { var responseMsg = ExceptionHandler( () => { User user; var context = new BlogSystemContext(); using (context) { user = context.Users.FirstOrDefault(u => u.SessionKey == sessionKey); if (user == null) { throw new InvalidOperationException("Invalid username or password"); } } Dictionary<string, Tag> tags = new Dictionary<string, Tag>(); foreach (var tag in model.Tags) { var tagToLower = tag.ToLower(); if (!tags.ContainsKey(tagToLower)) { Tag newTag = new Tag { Name = tagToLower }; tags.Add(tagToLower, newTag); } } var titleTags = model.Title.Split(' '); foreach (var tag in titleTags) { var tagToLower = tag.ToLower(); if (!tags.ContainsKey(tagToLower)) { Tag newTag = new Tag { Name = tagToLower }; tags.Add(tagToLower, newTag); } } List<Tag> filtTags = new List<Tag>(); foreach (var tag in tags.Values) { filtTags.Add(tag); } var newPost = new Post { Title = model.Title, Text = model.Text, Tags = filtTags, PostDate = DateTime.Now, User = user, }; var dbPost = this.postRepository.Add(newPost); var postMode = new CreatedPostModel { Id = dbPost.Id, Title = dbPost.Title }; var response = this.Request.CreateResponse(HttpStatusCode.Created, postMode); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = postMode.Id })); return response; }); return responseMsg; }