【问题标题】:What route to use in asp.net web api for deleting item from list in object在asp.net web api中使用什么路由从对象列表中删除项目
【发布时间】:2012-07-13 09:39:15
【问题描述】:

我在服务器上有一个名为 foo 的实体,它有一个分配给它的条形列表。我希望能够从 foo 中删除单个条。

但是,我不想更新客户端并发送整个 foo,因为 foo 是一个大对象,所以如果我只是从 foo 中删除一个 bar,那么每次发送都会有很多 Json。

我只想向下发送 bar 然后将其从 foo 实体中删除。

我有我的班级 foo

public class Foo
{
    public Foo()
    {
        Bars = new Collection<Bar>();    
    }

    public ICollection<Bar> Bars { get; set; }
}

我已经绘制了路线

routes.MapHttpRoute(
    name: "fooBarRoute",
    routeTemplate: "api/foo/{fooId}/bar/{barId}",
    defaults: new { controller = "Bar", action = "RemoveBarFromFoo" }
    );

通过 javascript (coffeescript) 发送请求

$.ajax(
url: api/foo/1/bar/1,
data: jsonData,
cache: false,
type: 'XXX',
....

我只是不确定要使用什么路由,我尝试过 PUT,但它不喜欢它,而且我可能做错了。我不确定在这种情况下我应该使用什么路线。

public class BarController : ApiController
{
    public void RemoveBarFromFoo(int fooId, Bar bar)
    {    
        // get the foo from the db and then remove the bar from the list and save
    }
}

我的问题:我应该使用什么途径来实现这个目标?或者,如果我以错误的方式解决这个问题,我应该怎么做?

谢谢,尼尔

【问题讨论】:

    标签: c# asp.net rest asp.net-web-api


    【解决方案1】:

    您使用的 HTTP 动词必须是 DELETE,动作名称必须是 Delete,以便遵循标准 RESTful 约定。此外,此操作不应将 Bar 对象作为参数。只有barId,因为这就是客户端发送的全部内容:

    public class BarController : ApiController
    {
        public void Delete(int fooId, int barId)
        {    
            // get the foo from the db and then remove the bar from the list and save
        }
    }
    

    然后你打电话:

    $.ajax({
        url: 'api/foo/1/bar/1',
        type: 'DELETE',
        success: function(result) {
    
        }
    });
    

    现在 yuo 可以从您的路由定义中删除该操作,因为它是 HTTP 动词,指示应该调用哪个操作:

    routes.MapHttpRoute(
        name: "fooBarRoute",
        routeTemplate: "api/foo/{fooId}/bar/{barId}",
        defaults: new { controller = "Bar" }
    );
    

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2013-07-14
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 2016-07-13
      • 1970-01-01
      • 2010-12-14
      • 1970-01-01
      相关资源
      最近更新 更多