Skip to content

Instantly share code, notes, and snippets.

@dileno
Last active September 12, 2019 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dileno/0c587170a6730247bba3980812248815 to your computer and use it in GitHub Desktop.
Save dileno/0c587170a6730247bba3980812248815 to your computer and use it in GitHub Desktop.
BlogPostsController
[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