Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Backend.Data;
- using Backend.Models;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- namespace Backend.Controllers
- {
- [ApiController]
- [Route("api/[controller]")]
- public class UsersController : ControllerBase
- {
- private readonly ApplicationDbContext _context;
- public UsersController(ApplicationDbContext context)
- {
- _context = context;
- }
- [HttpGet]
- public async Task<ActionResult<IEnumerable<User>>> GetUsers()
- {
- var users = await _context.Users.ToListAsync();
- return Ok(users);
- }
- [HttpGet("{id}")]
- public async Task<ActionResult<User>> GetUser(int id)
- {
- var user = await _context.Users.FindAsync(id);
- if(user == null)
- {
- return NotFound();
- }
- return Ok(user);
- }
- [HttpPost]
- public async Task<ActionResult<User>> PostUser(User user)
- {
- if (user == null)
- {
- return BadRequest("User data is required");
- }
- try
- {
- _context.Users.Add(user);
- await _context.SaveChangesAsync();
- return CreatedAtAction("GetUser", new {id = user.Id }, user);
- }
- catch (Exception ex)
- {
- return StatusCode(500, "En error occured while creatint user. Try again later");
- }
- }
- [HttpPut("{id}")]
- public async Task<IActionResult> PutUser(int id, User user)
- {
- if (id != user.Id)
- {
- return BadRequest();
- }
- _context.Entry(user).State = EntityState.Modified;
- try
- {
- await _context.SaveChangesAsync();
- }
- catch (DbUpdateConcurrencyException)
- {
- if (!UserExists(id))
- {
- return NotFound();
- }
- else
- {
- throw;
- }
- }
- return NoContent();
- }
- private bool UserExists(int id)
- {
- return _context.Users.Any(e => e.Id == id);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement