我正在使用MVC。当我运行调试器并使用Postman进行测试并将鼠标悬停在参数上时,它显示参数传递为MovieIds
的空值,但CustomerId
正在按预期工作。
Api控制器:newRental
在调试时显示MovieIds
为空
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进行硬编码并将其发送到数据库。
答案 0 :(得分:1)
正确猜测问题是MovieIds
是List<int>
,因此您的请求应该是这样的(使用括号[]
):
MovieIds: [1],