【因】api
WebAPI的Controller中,通常都是下面四種方法:post
對應於數據操做是咱們一般所說的CRUD.spa
C對應post,R對應Get,U對應Put,D對應Delete。3d
直接模仿VS 2012 WebAPI項目模板中的CRUD方法,R傳回的是要查的值,CUD都是空,這樣雖然也知足邏輯,code
可是一旦出錯,沒有有效的錯誤處理機制,如上一節Controller中的方法,雖然也能夠使用,但不適合做爲商用項目中的標準方法.對象
因此在此總結出較標準的CRUD方法模板,以供參考。blog
【果】it
改編自第一節中的CRUD方法io
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 else 14 { 15 msg = Request.CreateResponse<course>(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 else 13 { 14 ret.title = c.title; 15 msg = Request.CreateResponse<course>(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 else 14 { 15 courses.Remove(ret); 16 msg = Request.CreateResponse<course>(HttpStatusCode.Gone, ret); 17 } 18 return msg; 19 }