Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [Route("api/[controller]")]
- public class StudentsController : Controller
- {
- private readonly StudentContext _context;
- public StudentsController(StudentContext context)
- {
- _context = context;
- }
- [HttpGet("")]
- public IActionResult Get()
- {
- var allStudents = _context.Students.ToList();
- return Ok(allStudents);
- }
- [HttpGet("{id:int}")]
- public IActionResult Get(int id)
- {
- var student = _context.Students.SingleOrDefault(x => x.Id == id);
- if (student == null)
- {
- return NotFound();
- }
- return Ok(student);
- }
- [HttpPost("")]
- public IActionResult Post([FromBody] Student student)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- student.Id = 0;
- _context.Students.Add(student);
- _context.SaveChanges();
- return NoContent();
- }
- [HttpPut("{id:int}")]
- public IActionResult Put(int id, [FromBody] Student modifiedStudent)
- {
- if (!ModelState.IsValid)
- {
- return BadRequest(ModelState);
- }
- var student = _context.Students.SingleOrDefault(x => x.Id == id);
- if (student == null)
- {
- return NotFound();
- }
- student.FirstName = modifiedStudent.FirstName;
- student.LastName = modifiedStudent.LastName;
- _context.SaveChanges();
- return Ok(student);
- }
- [HttpDelete("{id:int}")]
- public IActionResult Delete(int id)
- {
- var studentToDelete = _context.Students.SingleOrDefault(x => x.Id == id);
- if (studentToDelete == null)
- {
- return NotFound();
- }
- _context.Students.Remove(studentToDelete);
- _context.SaveChanges();
- return NoContent();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement