web api
HttpResponseMessage 和 HttpResponseMessage
HttpResponseMessage 用于处理返回状态信息
HttpResponseMessage 用于发生错误信息时 404 505
自定义返回状态
1 public HttpResponseMessage dele(int id) 2 { 3 return Request.CreateResponse(HttpStatusCode.OK); 4 }
自定义状态码
public HttpResponseMessage dele(int id) { var resopnse = Request.CreateResponse(HttpStatusCode.OK); resopnse.StatusCode = HttpStatusCode.OK; resopnse.Content = new StringContent("状态值返回"); return resopnse; }
响应列举对象
public IEnumerable<product> Get() { List<product> lp = new List<product>() { new product() {name="xiaowang" }, new product() {name="xiaoli" } }; return lp; } public HttpResponseMessage dele(int id) { HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.OK ); message.Content = new ObjectContent<IEnumerable<product>>(Get(), new JsonMediaTypeFormatter()); return message; }
CreateResponse<T> 泛型的回应方法
public HttpResponseMessage dele(int id) { IEnumerable<product> ienu = Get(); var pro = ienu.Where(p => p.name == "xiaowang"); if (pro.FirstOrDefault<product>() != null) { return Request.CreateResponse<product>(HttpStatusCode.OK, pro.First<product>()); } else { throw new HttpResponseException(HttpStatusCode.NotFound); } }
自定义HttpResponseException
public HttpResponseMessage dele(int id) { var message = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("错误消息"), ReasonPhrase = "出错了" }; throw new HttpResponseException(message); }