【因】
WebAPI的Controller中,一般都是下面四种方法:
对应于数据操作是我们通常所说的CRUD.
C对应post,R对应Get,U对应Put,D对应Delete。
直接模仿VS 2012 WebAPI项目模板中的CRUD方法,R传回的是要查的值,CUD都是空,这样虽然也满足逻辑,
但是一旦出错,没有有效的错误处理机制,如上一节Controller中的方法,虽然也可以使用,但不适合作为商用项目中的标准方法.
所以在此总结出较标准的CRUD方法模板,以供参考。
【果】
改编自第一节中的CRUD方法
1.Read
1)GET api/courses/id
不同于以前返回的是要查找的对象,现在返回的是HttpResponseMessage对象,其中可以包含要返回的对象值,一旦出错,会有恰当的
错误代码及信息返回。
// GET api/courses/id
public HttpResponseMessage Get(int id)
{
HttpResponseMessage msg=null;
var ret=(from c in courses
where c.id==id
select c).FirstOrDefault();
//todo: if null- should return 404
if (ret == null)
{
msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");
}
else
{
msg = Request.CreateResponse<course>(HttpStatusCode.OK, ret);
}
return msg;
}
2.Create
Post api/courses/
// Post api/courses
public HttpResponseMessage Post([FromBody]course c)
{
c.id = courses.Count;
courses.Add(c);
//TODO:: should return a 201 with a location head
var msg = Request.CreateResponse(HttpStatusCode.Created);
msg.Headers.Location = new Uri(Request.RequestUri + c.id.ToString());
return msg;
}
3.Update
// Put api/courses/id
public HttpResponseMessage Put(int id, [FromBody]course c)
{
HttpResponseMessage msg = null;
var ret = (from v in courses
where v.id == c.id
select v).FirstOrDefault();
if (ret == null)
{
msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");
}
else
{
ret.title = c.title;
msg = Request.CreateResponse<course>(HttpStatusCode.Accepted, ret);
msg.Headers.Location = new Uri(Request.RequestUri + c.id.ToString());
}
return msg;
}
4.Delete
// Delete api/courses/id
public HttpResponseMessage Delete(int id)
{
HttpResponseMessage msg = null;
var ret = (from c in courses
where c.id == id
select c).FirstOrDefault(); if (ret == null)
{
msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");
}
else
{
courses.Remove(ret);
msg = Request.CreateResponse<course>(HttpStatusCode.Gone, ret);
}
return msg;
}