HttpResponseMessage 和 HttpResponseMessage
HttpResponseMessage 用於處理返回狀態信息
HttpResponseMessage 用於發生錯誤信息時 404 505
自定義返回狀態
public HttpResponseMessage dele(int id) { return Request.CreateResponse(HttpStatusCode.OK); }
自定義狀態碼
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); }