我正在尝试从Web API
客户端Web服务类调用MVC5
Put方法。我可以通过它的id来编辑本书,但是当我编辑任何内容时,我会收到此错误
响应状态代码不表示成功:500(内部服务器错误)。
我已经搜索了一些有关导致此错误的信息,但我无法找到实际问题。有人可以帮忙指出我做错了什么。
API控制器
// PUT: api/Books/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> Put(int id, BookDetailDTO book)
{
try{
var bookEdit = db.Books.FirstOrDefault(b => b.Id == id);
if(bookEdit == null){
return BadRequest();
}
else{
bookEdit.Title = book.Title;
bookEdit.Year = book.Year;
bookEdit.Price = book.Price;
bookEdit.Author.Name = book.AuthorName;
bookEdit.Genre = book.Genre;
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = book.Id }, bookEdit);
}
}
catch{
if (!BookExists(id)){
return NotFound();
}
else{
throw;
}
}
}
BookService方法
public void UpdateBook(int? id, BookDetailDTO book)
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + MyToken.myToken);
BookDetailDTO bookDetailDTO = new BookDetailDTO();
bookDetailDTO.Id = book.Id;
bookDetailDTO.Title = book.Title;
bookDetailDTO.Year = book.Year;
bookDetailDTO.Genre = book.Genre;
bookDetailDTO.Price = book.Price;
bookDetailDTO.AuthorName = book.AuthorName;
HttpResponseMessage responseMessage = client.PutAsJsonAsync(url + "/" + id, bookDetailDTO).Result;
responseMessage.EnsureSuccessStatusCode();
}
预订DTO
课程
public class BookDetailDTO
{
public int Id { get; set; }
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string AuthorName { get; set; }
public string Genre { get; set; }
}
预订模型
public class Book
{
public int Id { get; set; }
[Required]
public string Title { get; set; }
public int Year { get; set; }
public decimal Price { get; set; }
public string Genre { get; set; }
// Foreign Key
public int AuthorId { get; set; }
//public virtual IEnumerable<Author> AuthorID { get; set; }
// Navigation property
public virtual Author Author { get; set; }
}