Last active
September 12, 2019 10:26
-
-
Save dileno/0c587170a6730247bba3980812248815 to your computer and use it in GitHub Desktop.
BlogPostsController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Route("api/[controller]")] | |
[Produces("application/json")] | |
[ApiController] | |
public class BlogPostsController : ControllerBase | |
{ | |
private readonly BlogPostsContext _context; | |
public BlogPostsController(BlogPostsContext context) | |
{ | |
_context = context; | |
} | |
// GET: api/BlogPosts | |
[HttpGet] | |
public async Task<ActionResult<IEnumerable<BlogPost>>> GetBlogPost() | |
{ | |
return await _context.BlogPosts.ToListAsync(); | |
} | |
// GET: api/BlogPosts/5 | |
[HttpGet("{id}")] | |
public async Task<ActionResult<BlogPost>> GetBlogPost(int id) | |
{ | |
var blogPost = await _context.BlogPosts.FindAsync(id); | |
if (blogPost == null) | |
{ | |
return NotFound(); | |
} | |
return blogPost; | |
} | |
// PUT: api/BlogPosts/5 | |
[HttpPut("{id}")] | |
public async Task<IActionResult> PutBlogPost(int id, BlogPost blogPost) | |
{ | |
if (id != blogPost.PostId) | |
{ | |
return BadRequest(); | |
} | |
_context.Entry(blogPost).State = EntityState.Modified; | |
try | |
{ | |
await _context.SaveChangesAsync(); | |
} | |
catch (DbUpdateConcurrencyException) | |
{ | |
if (!BlogPostExists(id)) | |
{ | |
return NotFound(); | |
} | |
else | |
{ | |
throw; | |
} | |
} | |
return NoContent(); | |
} | |
// POST: api/BlogPosts | |
[HttpPost] | |
public async Task<ActionResult<BlogPost>> PostBlogPost(BlogPost blogPost) | |
{ | |
_context.BlogPosts.Add(blogPost); | |
await _context.SaveChangesAsync(); | |
return CreatedAtAction("GetBlogPost", new { id = blogPost.PostId }, blogPost); | |
} | |
// DELETE: api/BlogPosts/5 | |
[HttpDelete("{id}")] | |
public async Task<ActionResult<BlogPost>> DeleteBlogPost(int id) | |
{ | |
var blogPost = await _context.BlogPosts.FindAsync(id); | |
if (blogPost == null) | |
{ | |
return NotFound(); | |
} | |
_context.BlogPosts.Remove(blogPost); | |
await _context.SaveChangesAsync(); | |
return blogPost; | |
} | |
private bool BlogPostExists(int id) | |
{ | |
return _context.BlogPosts.Any(e => e.PostId == id); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment