Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions MyFirstBlog/Controllers/PostsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,21 @@ public ActionResult<PostDto> 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 } });
}
}
21 changes: 21 additions & 0 deletions MyFirstBlog/Services/PostService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ public interface IPostService
{
IEnumerable<PostDto> GetPosts();
PostDto GetPost(String slug);

PostDto CreatePost(PostDto postDto);
}

public class PostService : IPostService
Expand All @@ -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();
}
}
2 changes: 1 addition & 1 deletion MyFirstBlog/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -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": {
Expand Down