【因】
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对象,其中可以包含要返回的对象值,一旦出错,会有恰当的
错误代码及信息返回。
1 // GET api/courses/id 2 public HttpResponseMessage Get(int id) 3 { 4 HttpResponseMessage msg=null; 5 var ret=(from c in courses 6 where c.id==id 7 select c).FirstOrDefault(); 8 //todo: if null- should return 404 9 if (ret == null)10 {11 msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");12 }13 else14 {15 msg = Request.CreateResponse(HttpStatusCode.OK, ret);16 }17 return msg;18 }
2.Create
Post api/courses/
1 // Post api/courses 2 public HttpResponseMessage Post([FromBody]course c) 3 { 4 c.id = courses.Count; 5 courses.Add(c); 6 //TODO:: should return a 201 with a location head 7 var msg = Request.CreateResponse(HttpStatusCode.Created); 8 msg.Headers.Location = new Uri(Request.RequestUri + c.id.ToString()); 9 return msg;10 }
3.Update
1 // Put api/courses/id 2 public HttpResponseMessage Put(int id, [FromBody]course c) 3 { 4 HttpResponseMessage msg = null; 5 var ret = (from v in courses 6 where v.id == c.id 7 select v).FirstOrDefault(); 8 if (ret == null) 9 {10 msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");11 }12 else13 {14 ret.title = c.title;15 msg = Request.CreateResponse(HttpStatusCode.Accepted, ret);16 msg.Headers.Location = new Uri(Request.RequestUri + c.id.ToString());17 }18 return msg;19 }
4.Delete
1 // Delete api/courses/id 2 public HttpResponseMessage Delete(int id) 3 { 4 HttpResponseMessage msg = null; 5 var ret = (from c in courses 6 where c.id == id 7 select c).FirstOrDefault(); 8 9 if (ret == null)10 {11 msg = Request.CreateErrorResponse(HttpStatusCode.NotFound, "Course not found");12 }13 else14 {15 courses.Remove(ret);16 msg = Request.CreateResponse(HttpStatusCode.Gone, ret);17 }18 return msg;19 }