I have a get, create, delete, and update method using automapper and Dtos in an asp.net web api I created, but for some reason I can't get the update method to work in postman. I select Put in postman and change values in one of the tables like for instance
{
"id": 3,
"movieTitle": "Movie 1",
"genreId": 3,
"releaseDate": "1977-05-02T00:00:00"
}
to
{
"id": 3,
"movieTitle": "Movie 11",
"genreId": 3,
"releaseDate": "1977-05-02T00:00:00"
}
But the values never update when I hit send in postman. I'm not understanding what I'm doing wrong since I have the id as the same. All the other methods are working, but not the update method. No exception/error is thrown. Any help is greatly appreciated.
[HttpPut]
public IHttpActionResult UpdateMovie(int id, MovieDto movieDto)
{
if (!ModelState.IsValid)
return BadRequest();
var movieInDb = _context.Movie.SingleOrDefault(c => c.Id == id);
if (movieInDb == null)
return NotFound();
Mapper.Map(movieDto, movieInDb);
_context.SaveChanges();
return Ok();
}
Whole Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AutoMapper;
using Vidly1.Dtos;
using Vidly1.Models;
namespace Vidly1.Controllers.Api
{
public class MoviesController : ApiController
{
private ApplicationDbContext _context;
public MoviesController()
{
_context = new ApplicationDbContext();
}
public IEnumerable<MovieDto> getMovies()
{
return _context.Movie.ToList().Select(Mapper.Map<Movie, MovieDto>);
}
[HttpGet]
public IHttpActionResult GetMovie(int id)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var movie = _context.Movie.SingleOrDefault(m => m.Id == id);
if (movie == null)
{
return NotFound();
}
return Ok(Mapper.Map<Movie, MovieDto>(movie));
}
[HttpPost]
public IHttpActionResult CreateMovie(MovieDto movieDto)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var movie = Mapper.Map<MovieDto, Movie>(movieDto);
if (movie == null)
{
return NotFound();
}
_context.Movie.Add(movie);
_context.SaveChanges();
movieDto.Id = movie.Id;
return Created(new Uri(Request.RequestUri + "/" + movie.Id), movieDto);
}
[HttpPut]
public IHttpActionResult UpdateMovie(int id, MovieDto movieDto)
{
if (!ModelState.IsValid)
return BadRequest();
var movieInDb = _context.Movie.SingleOrDefault(c => c.Id == id);
if (movieInDb == null)
return NotFound();
Mapper.Map(movieDto, movieInDb);
_context.SaveChanges();
return Ok();
}
[HttpDelete]
public void DeleteMovie(int id, MovieDto movieDto)
{
if (!ModelState.IsValid)
{
throw new HttpResponseException(HttpStatusCode.BadRequest);
}
var movie = _context.Movie.SingleOrDefault(m => m.Id == id);
if (movie == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
_context.Movie.Remove(movie);
_context.SaveChanges();
}
}
}