Advertisement
Guest User

Untitled

a guest
Jan 21st, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1.  
  2. [Route("api/[controller]")]
  3. public class StudentsController : Controller
  4. {
  5. private readonly StudentContext _context;
  6.  
  7. public StudentsController(StudentContext context)
  8. {
  9. _context = context;
  10. }
  11.  
  12. [HttpGet("")]
  13. public IActionResult Get()
  14. {
  15. var allStudents = _context.Students.ToList();
  16. return Ok(allStudents);
  17. }
  18.  
  19. [HttpGet("{id:int}")]
  20. public IActionResult Get(int id)
  21. {
  22. var student = _context.Students.SingleOrDefault(x => x.Id == id);
  23. if (student == null)
  24. {
  25. return NotFound();
  26. }
  27. return Ok(student);
  28. }
  29.  
  30. [HttpPost("")]
  31. public IActionResult Post([FromBody] Student student)
  32. {
  33. if (!ModelState.IsValid)
  34. {
  35. return BadRequest(ModelState);
  36. }
  37. student.Id = 0;
  38. _context.Students.Add(student);
  39. _context.SaveChanges();
  40. return NoContent();
  41. }
  42.  
  43. [HttpPut("{id:int}")]
  44. public IActionResult Put(int id, [FromBody] Student modifiedStudent)
  45. {
  46. if (!ModelState.IsValid)
  47. {
  48. return BadRequest(ModelState);
  49. }
  50. var student = _context.Students.SingleOrDefault(x => x.Id == id);
  51. if (student == null)
  52. {
  53. return NotFound();
  54. }
  55. student.FirstName = modifiedStudent.FirstName;
  56. student.LastName = modifiedStudent.LastName;
  57. _context.SaveChanges();
  58. return Ok(student);
  59. }
  60.  
  61. [HttpDelete("{id:int}")]
  62. public IActionResult Delete(int id)
  63. {
  64. var studentToDelete = _context.Students.SingleOrDefault(x => x.Id == id);
  65. if (studentToDelete == null)
  66. {
  67. return NotFound();
  68. }
  69. _context.Students.Remove(studentToDelete);
  70. _context.SaveChanges();
  71. return NoContent();
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement