diff --git a/MyFirstBlog/Controllers/PostsController.cs b/MyFirstBlog/Controllers/PostsController.cs index 8fa6bf2c..fa6255cc 100644 --- a/MyFirstBlog/Controllers/PostsController.cs +++ b/MyFirstBlog/Controllers/PostsController.cs @@ -31,4 +31,21 @@ public ActionResult GetPost(string slug) { return post; } + + // POST /posts + [HttpPost] + public IActionResult CreatePost([FromBody] PostDto postDto) + { + // simple validation + if (string.IsNullOrWhiteSpace(postDto.Title)) + { + return BadRequest(new { errors = new[] { "Title cannot be blank" } }); + } + + // use the service to create post + var createdPost = _postService.CreatePost(postDto); + + // return 201 Created with the new post + return Created("", new { post = new { createdPost.Title, createdPost.Body } }); + } } diff --git a/MyFirstBlog/Services/PostService.cs b/MyFirstBlog/Services/PostService.cs index 6bac099f..d1eef6ae 100644 --- a/MyFirstBlog/Services/PostService.cs +++ b/MyFirstBlog/Services/PostService.cs @@ -9,6 +9,8 @@ public interface IPostService { IEnumerable GetPosts(); PostDto GetPost(String slug); + + PostDto CreatePost(PostDto postDto); } public class PostService : IPostService @@ -34,4 +36,23 @@ private Post getPost(string slug) { return _context.Posts.Where(a=>a.Slug==slug.ToString()).SingleOrDefault(); } + + public PostDto CreatePost(PostDto postDto) + { + // create a simple slug from the title + var slug = Regex.Replace(postDto.Title.ToLower(), @"\s+", "-"); + + var newPost = new Post + { + Title = postDto.Title, + Body = postDto.Body, + Slug = slug, + CreatedDate = DateTime.UtcNow + }; + + _context.Posts.Add(newPost); + _context.SaveChanges(); + + return newPost.AsDto(); + } } diff --git a/MyFirstBlog/appsettings.Development.json b/MyFirstBlog/appsettings.Development.json index 68bd7dc3..91574de9 100644 --- a/MyFirstBlog/appsettings.Development.json +++ b/MyFirstBlog/appsettings.Development.json @@ -1,6 +1,6 @@ { "ConnectionStrings": { - "DefaultConnection": "Host=localhost; Database=bvc-blog; Username=postgres; Password=postgres" + "DefaultConnection": "Host=localhost; Database=bvc-blog; Username=postgres; Password=1111" }, "Logging": { "LogLevel": {