首页 > 代码库 > HTTP请求返回类

HTTP请求返回类

  在学习《构建具有CRUD功能的ASP.NET Web API》一文中,通过产品ID获得产品信息的方法如下:

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进行返回,具体代码如下:

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 }

调试通过