public HttpResponseMessage PostProduct(Product product) { productList.Add(product); // string apiName = ApiDemo.WebApiConfig.DEFAULT_ROUTE_NAME; var response = this.Request.CreateResponse<Product>(HttpStatusCode.Created, product); string uri = Url.Link("DefaultApi", new { id = product.Id }); //DefaultApi 为WebApiConfig中的路由名称 response.Headers.Location = new Uri(uri); return response; }
public bool PutProduct(Product product) { try { Product updatePro = products.First<Product>(obj => obj.Id == product.Id); updatePro.Name = product.Name; } catch { throw new HttpResponseException(HttpStatusCode.NotFound); } return true; }
static void Main(string[] args) { System.Threading.Thread.Sleep(100); Console.Clear(); Console.WriteLine("**************************开始执行获取API***********************************"); HttpClient client = new HttpClient(); //Get All Product 获取所有 HttpResponseMessage responseGetAll = client.GetAsync(url + "api/Products").Result; string GetAllProducts = responseGetAll.Content.ReadAsStringAsync().Result; Console.WriteLine("GetAllProducts方法:" + GetAllProducts); //Get Product根据ID获取 HttpResponseMessage responseGetID = client.GetAsync(url + "api/Products/1").Result; string GetProduct = responseGetID.Content.ReadAsStringAsync().Result; Console.WriteLine("GetProduct方法:" + GetProduct); //Delete Product 根据ID删除 HttpResponseMessage responseDeleteID = client.DeleteAsync(url + "api/Products/1").Result; // string DeleteProduct = responseDeleteID.Content.ReadAsStringAsync().Result; Console.WriteLine("DeleteProduct方法:" ); //HttpContent abstract 类 //Post Product 添加Product对象 var model = new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }; HttpContent content = new ObjectContent(typeof(Product), model, new JsonMediaTypeFormatter()); client.PostAsync(url + "api/Products/", content); //Put Product 修改Product client.PutAsync(url + "api/Products/", content); Console.ReadKey(); }