我正在使用MVC.当我运行调试器并使用Postman进行测试并将鼠标悬停在参数上时,它显示参数传递给MovieIds的空值,但CustomerId正在按预期工作.
Api Controller:newRental在调试时将MovieIds显示为null
public class NewRentalsController : ApiController
{
private ApplicationDbContext _context;
public NewRentalsController()
{
_context = new ApplicationDbContext();
}
[HttpPost]
public IHttpActionResult CreateNewRentals(NewRentalDto newRental)
{
var customer = _context.Customers.Single(c => c.Id == newRental.CustomerId);
var movies = _context.Movies.Where(m => newRental.MovieIds.Contains(m.Id)).ToList();
//var movies = _context.Movies.Where(m => m.Id ==1);
foreach (var movie in movies)
{
if (movie.NumberAvailable == 0)
return BadRequest("Movie is not available.");
movie.NumberAvailable--;
var rental = new Rental
{
Customer = customer,
Movie = movie,
DateRented = DateTime.Now
};
_context.Rentals.Add(rental);
}
_context.SaveChanges();
return Ok();
}
}
DTO:
public class NewRentalDto
{
public int CustomerId { get; set; }
public List<int> MovieIds { get; set; }
}
邮差要求:
{"customerId": 2,
"movieId": 1,
"dateRented": "2017-09-28T00:00:00"
}
我认为这与List< int>有关.因为我可以硬编码Id,它会将它发送到数据库.
最佳答案 正如你猜测的那样,问题是MovieIds是一个List< int>所以你的请求应该是这样的(使用方括号[]):
MovieIds: [1],