我在服务器上有一个名为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
}
}
我的问题是:我应该使用什么方法来实现这个目标?或者,如果我走错了路,我该怎么办?
谢谢,尼尔
发布于 2012-07-13 09:47:20
为了遵循标准的RESTful约定,您正在使用的HTTP谓词必须是DELETE,操作名称必须是Delete
。此外,此操作不应将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) {
}
});
现在,您可以从您的路由定义中删除操作,因为它是HTTP动词,指示应该调用哪个操作:
routes.MapHttpRoute(
name: "fooBarRoute",
routeTemplate: "api/foo/{fooId}/bar/{barId}",
defaults: new { controller = "Bar" }
);
https://stackoverflow.com/questions/11467897
复制相似问题