private static void AddCustomer(Customer customer) { if (!customers.TryAdd(customer.Id, customer)) { HttpResponseMessage response = new HttpResponseMessage(); response.StatusCode = HttpStatusCode.Conflict; response.Content = new StringContent(string.Format("There already a customer with id '{0}'.", customer.Id)); throw new HttpResponseMessageException(response); } }
private static HttpResponseMessage GetResponseForCustomer(Customer customer) { return new HttpResponseMessage() { StatusCode = HttpStatusCode.OK, Content = new StringContent(SerializeCustomer(customer)) }; }
private static string SerializeCustomer(Customer customer) { return string.Format("Id = {0}; Name = {1}", customer.Id, customer.Name); }
private static Customer GetCustomerFromRequest(HttpRequestMessage request) { if (request.Content == null) { HttpResponseMessage noContentResponse = new HttpResponseMessage(); noContentResponse.StatusCode = HttpStatusCode.BadRequest; noContentResponse.Content = new StringContent("Expected an entity body with customer data but no content was found."); throw new HttpResponseMessageException(noContentResponse); } string content = request.Content.ReadAsString(); string[] contentSplit = content.Split('=', ';'); if (contentSplit.Length == 4) { if (string.Equals(contentSplit[0].Trim(), "Id", StringComparison.OrdinalIgnoreCase) && string.Equals(contentSplit[2].Trim(), "Name", StringComparison.OrdinalIgnoreCase)) { Customer customer = new Customer(); int id; if (int.TryParse(contentSplit[1].Trim(), out id)) { customer.Id = id; customer.Name = contentSplit[3].Trim(); return customer; } } } HttpResponseMessage faileParseResponse = new HttpResponseMessage(); faileParseResponse.StatusCode = HttpStatusCode.BadRequest; faileParseResponse.Content = new StringContent("Parsing the entity body as a customer failed."); throw new HttpResponseMessageException(faileParseResponse); }