[英]JSON Array response REST API, Error extracting data c#
[英]C# REST API - returning an array as JSON
我正在嘗試構建 REST API。 我一直在使用 Microsoft Docs 的本指南,希望能得到一些幫助。
我有 2 個模型庫和書籍。 每個人都有自己的控制器。
我希望每個人都能相互引用,這樣我就可以獲取圖書館中的所有書籍,並且我想要一本書來引用它所屬的圖書館。 我正在使用 Microsoft Entity Framework 的內存數據庫
我當前的 model 類如下所示:
圖書館:
public class Library
{
[Key]
public long id { get; set; }
public Book[] bookArray { get; set; }
public string postalCode { get; set; }
public string street { get; set; }
public string city { get; set; }
public string country { get; set; }
}
書:
public class Book
{
[Key]
public long id { get; set; }
public long libraryId { get; set; }
public string title { get; set; }
public string author { get; set; }
public string description { get; set; }
}
我想要一個像“api/Libraries/{id}/books”這樣的 GET 端點,它將圖書館內的書籍數組返回為 JSON,但我無法返回該數組。 我收到錯誤“無法將 Models.Book 隱式轉換為 Microsoft.AspNetCore.Mvc.ActionResult<A2.Models.Library>”。 我是否正確設置了 model 類? 以及如何解決此錯誤。
編碼:
// GET: api/Libraries/5/books
[HttpGet("{id}/books")]
public async Task<ActionResult<Library>> GetLibraryBooks(long id)
{
var library = await _context.Libraries.FindAsync(id);
if (library == null)
{
return NotFound();
}
return library.bookArray;
}
您的方法應該像這樣返回Book[]
:
[HttpGet("{id}/books")]
public async Task<ActionResult<Book[]>> GetLibraryBooks(long id)
{
var library = await _context.Libraries.FindAsync(id);
if (library == null)
{
return NotFound();
}
return Ok(library.bookArray);
}
更新
public class Library
{
public Libary(){
books = new List<Book>();
}
[Key]
public long id { get; set; }
public List<Book> books { get; set; }
public string postalCode { get; set; }
public string street { get; set; }
public string city { get; set; }
public string country { get; set; }
}
更新 2
public class LibraryController : Controller
{
private readonly LibraryContext _context;
public LibraryController(LibraryContext context)
{
_context = context;
}
[HttpPost("{id}")]
public IActionResult AddBookToLibrary([FromRoute]long id ,[FromBody] Book bookToAdd)
{
var libraryToAddBook = _context.Libraries.Include(l => l.books)
.FirstOrDefault(l => l.id == id);
if (libraryToAddBook == null)
return NotFound();
libraryToAddBook.books.Add(bookToAdd);
_context.SaveChanges();
return Ok();
}
}
更新的上下文
public class LibraryContext : DbContext
{
public LibraryContext(DbContextOptions<LibraryContext> options)
: base(options)
{
}
public DbSet<Library> Libraries { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Library>()
.OwnsMany<Book>(l => l.books);
}
}
啟動.cs
var connectionString = Configuration.GetConnectionString("myDatabaseConnectionString");
services.AddDbContext<LibraryContext>(options =>
{
//options.USEYOURDATABASE(connectionString); //you might need install a NuGet eg. Microsoft.EntityFrameworkCore.SqlServer
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.