An0n0ym0usHacker

BlogPostsController

Jul 29th, 2021 (edited)
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.06 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6.  
  7. using BlogAPI.Models;
  8. using BlogAPI.Services;
  9. using BlogAPI.Attributes;
  10.  
  11. namespace BlogAPI.Controllers
  12. {
  13.     [ApiKey]
  14.     [Route("api/[controller]")]
  15.     [ApiController]
  16.     public class BlogPostsController : ControllerBase
  17.     {
  18.         readonly BlogContext _context;
  19.         public BlogPostsController(BlogContext context)
  20.         {
  21.             _context = context;
  22.         }
  23.  
  24.         //GET api/blogposts
  25.         [HttpGet]
  26.         public ActionResult<IEnumerable<BlogPost>> Get()
  27.         {
  28.             return _context.BlogPosts;
  29.         }
  30.  
  31.         //GET api/blogposts/5
  32.         [HttpGet("{id}")]
  33.         public ActionResult<BlogPost> Get(int id)
  34.         {
  35.             return _context.BlogPosts.FirstOrDefault(post => post.BlogPostId == id);
  36.         }
  37.  
  38.         //POST api/blogposts
  39.         [HttpPost]
  40.         public void Post([FromBody] BlogPost value)
  41.         {
  42.             _context.BlogPosts.Add(value);
  43.             _context.SaveChanges();
  44.  
  45.         }
  46.  
  47.         //PUT api/blogposts/5
  48.         [HttpPut("{id}")]
  49.         public void Put(int id, [FromBody] BlogPost value)
  50.         {
  51.             var post = _context.BlogPosts.FirstOrDefault(p => p.BlogPostId == id);
  52.             if(post == null)
  53.                 return;
  54.             post.Title = value.Title;
  55.             post.Summary = value.Summary;
  56.             post.Body = value.Body;
  57.             post.Author = value.Author;
  58.             post.Category = value.Category;
  59.             post.Tags = value.Tags;
  60.  
  61.             _context.BlogPosts.Update(post);
  62.             _context.SaveChanges();
  63.  
  64.         }
  65.  
  66.         //DELETE api/blogposts/5
  67.         [HttpDelete("{id}")]
  68.         public void Delete(int id)
  69.         {    
  70.             var post = _context.BlogPosts.FirstOrDefault(p => p.BlogPostId == id);
  71.             if(post == null)
  72.                 return;
  73.            
  74.             _context.BlogPosts.Remove(post);
  75.             _context.SaveChanges();
  76.  
  77.         }
  78.  
  79.     }
  80. }
Add Comment
Please, Sign In to add comment