WebAPI如何处理嵌套资源? [英] WebAPI how to deal with nested resources?

查看:330
本文介绍了WebAPI如何处理嵌套资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用WebAPI 2时,我正在寻找有关最佳实践的建议和建议.

i am looking for advice and suggestions on best practices when working with WebAPI 2:

让我们说我有两个控制器(用户和书籍),并且想接受这些路线:

Lets say i have two controllers(users and books), and that would like to accept these routes:

/users/{user_id}/books <= books owned by user_id

/books <= all books
/books/{book_id} <= book from id

专门处理/users/{user_id}/books的最佳实践是什么?我正在使用REST API处理大量自定义路由,因此我在方法上使用了[RoutePrefix]和[Verb,Route].

What would be the best practice on dealing with the /users/{user_id}/books specifically? I am dealing with a lot of custom routes in a REST API, so i use [RoutePrefix] and [Verb, Route] on methods.

非常感谢!我一直在努力为常见情况找到更好的解决方案和实践.

Thanks a lot in advance! I am always trying to find better solutions and practices to common situations.

推荐答案

我喜欢将所有返回实体的路由放在同一控制器上.因此,BooksController将如下所示:

I like to put all my routes for the returned entity on the same controller. So a BooksController would look like this:

public sealed class BooksController : ApiController
{
    //Ideally this Repository would be a dependency injected object
    private readonly IRepository<Book> _repo = new BooksRepo(); 

    [Route("books")]
    [HttpGet]
    public IQueryable<Book> GetAll()
    {
        return _repo.GetAll();
    }

    [Route("books/{bookId:int}")]
    [HttpGet]
    public Book GetById(int bookId)
    {
        return _repo.GetById(bookId);
    }

    [Route("users/{userId:int}/books")]
    [HttpGet]
    public IQueryable<Book> GetBooksByUser(int userId)
    {
        return _repo.GetByUser(userId);
    }

    [Route("users/{userId:int}/books/{bookId:int}")]
    [HttpGet]
    public Book GetUsersBook(int userId, int bookId)
    {
        return _repo.GetByUser(userId).FirstOrDefault(book => book.Id == bookId);
    }
}

现在,所有返回Books的路由都应在此控制器上.任何返回用户的路由都将放置在UsersController上.由于可以将Route属性放置在任何控制器上,这可以帮助我们使事情井井有条并得到简化.您可以很容易地在任何控制器上定义任何路由,从而很难跟踪所有可能的路由.

Now any route that returns Books should be on this controller. Any route that returns Users would be placed on the UsersController. This has helped us keep things organized and simplified since a Route attribute can be placed on any controller, you can very easily have any route defined on any controller that makes it difficult track down all the possible routes.

这篇关于WebAPI如何处理嵌套资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆