How would I use MVC4 WebAPI to chain controllers?
-
29-10-2019 - |
Вопрос
So my data model has something like this: Author.Books where a single Author can have multiple Books associated with it.
I can retrieve an Author with this route: /api/Authors/4 ... and I can get a list of all books like: /api/Books, or a single book like /api/Books/8
So how would I get all the books for a single Author? something like: /Authors/4/Books I don't know what needs to happen to enable the "/Books" part of that example. Do I modify the BooksController (and how)? Or the AuthorsController? Or... ?
Решение
You should seriously consider using the Powerful Odata translation capabilities of the web Api. It allows you to build rich queries directly in the querystring that are translated to a Linq expression. This is how I would solve your problem.
First, ensure that your book model has an AuthorId Property:
public class Book
{
public string Title{get; set;}
public int AuthorId{get; set;}
}
Next, create a books controller and expose the Get method that returns an IQueryable:
public class BooksController : ApiController
{
public IQueryable<Books> Get()
{
var books = new List
{
new Book{Title = "Book 1", AuthorId = 1},
new Book{Title = "Book 2", AuthorId = 2},
};
return books.AsQueryable();
}
}
Finally, to query a book by a particular author your URI will look as such:
/books?$filter=AuthorId eq 2