【问题标题】:Handle collections inside collections in Web API using ASP .Net MVC4使用 ASP .Net MVC 4 处理 Web API 中的集合和集合
【发布时间】:2012-05-21 22:21:00
【问题描述】:

我在我的机器上安装了新的 ASP .Net MVC4 测试版,并且一直在尝试了解 Web API 的工作原理。我为单个集合(例如书籍)构建了一个演示。我按照 asp.net 网站上的示例进行操作。我实现了自己的发布到集合的方法,即添加新书、获取所有书籍、获取特定书籍、更新书籍和删除书籍记录。这一切都很好。

例如:

POST /books - adds a new book
GET /books - gets all books
GET /books/1 - get a particular book
PUT /books/1 - update a particular book
DELETE /books/1 - delete a particular book

现在我想在书籍集合中添加另一个集合,比如作者,并希望为新集合实现相同的 POST、PUT、GET 和 DELETE 调用

我希望新的调用是这样的:

POST /books/1/authors - add a new author to a book
GET /books/1/authors - gets all authors of a book
GET /books/1/authors/a@a.com - get a particular author for a book
PUT /books/1/authors/a@a.com - update a particular author for a book
DLETE /books/1/authors/a@a.com - delete a particular author for a book

我很困惑如何添加路由以使此调用正常工作。默认情况下,我通过项目获得这条路线。

routes.MapHttpRoute(
name: "DefaultApi", 
routeTemplate: "api/{controller}/{id}", 
defaults: new { id = RouteParameter.Optional }
);

在这种模式下,为集合和它们之间的关联处理路由的正确方法是什么?

【问题讨论】:

    标签: asp.net asp.net-mvc-4


    【解决方案1】:

    在 Global 中管理路由可能会令人困惑且容易出错。就个人而言,我发现 Attribute Routing 包有助于大大简化路由配置。本文介绍了如何获取和使用它。

    http://www.strathweb.com/2012/05/attribute-based-routing-in-asp-net-web-api/

    【讨论】:

    • 我以前在全局中手动完成,我还尝试了基于属性的方法,效果很好。感谢您指出。
    【解决方案2】:

    我认为 Ken 使用 Attribute Routing 的方法更好,我是从这篇文章中发现的,我自己可能也会使用它。但这是我在了解 AR 之前想到的。

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "JustController",
                routeTemplate: "api/Books/{bookId}/{category}/{categoryId}/{subCategory}",
                defaults: new
                {
                    controller = "books",
                    bookId= RouteParameter.Optional,
                    category = RouteParameter.Optional,
                    categoryId = RouteParameter.Optional,
                    subCategory = RouteParameter.Optional
                },
                constraints: new
                {
                    bookId= @"\d*",
                    category= @"(|authors|pictures|videos)", 
                    categoryId = @"\d*",
                    subCategory = @"(|comments)"
                }
            );
    

    然后我就想在Get、Post、Delete、Put函数中使用Request属性中的URL,获取我需要的参数。

    例如:

        public class BooksController : ApiController
        {
            // GET api/books
            public Book Get(int bookId)
            {
             var url = this.Request.RequestUri.ToString() // decide how to handle!
    

    【讨论】:

    • 是的,我之前正在做类似的事情。就像你提到的基于属性的路由更干净,更容易管理路由。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 2012-11-15
    • 2012-03-27
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多