首页 > 代码库 > 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 }
调试通过
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。