HTTP请求返回类

  在学习《构建具备CRUD功能的ASP.NET Web API》一文中,经过产品ID得到产品信息的方法以下:web

1 public Product GetProduct(int id)
2 {
3     Product item = repository.Get(id);
4     if (item == null)
5     {
6         throw new HttpResponseException(HttpStatusCode.NotFound); 
7     }
8     return item;
9 }

  但在调试过程当中,若查出item为null,则程序在第8行报错,提示没有对对象为null的状况进行处理,经过在网上查找资料,并结合处理mvc 4 web api中没有IHttpActionResult接口的方法,采用HttpResponseMessage进行返回,具体代码以下:api

1 public HttpResponseMessage GetProduct(int id)
2 {
3     Product item = repository.Get(id);
4     if (item == null)
5     {
6         return Request.CreateResponse(HttpStatusCode.NotFound); 
7     }
8     return Request.CreateResponse(HttpStatusCode.OK, item);
9 }

调试经过mvc

相关文章
相关标签/搜索