// POST api/Artist public HttpResponseMessage PostArtist(Artist artist) { ////header //User-Agent: Fiddler //Host: localhost: ***** //Content-type: application/json //Content-Length: 77 ////request body //{ //"Name": "Pesho", //"Country": "Bulgaria", //"DateOfBirth": "1942.01.01" //} if (ModelState.IsValid) { db.Artists.Add(artist); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, artist); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = artist.ArtistId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }
private static Artist CreateArtistObject(int id, string name, string country, DateTime? date) { Artist newArtist = new Artist() { ArtistId = id, Name = name, Country = country, DateOfBirth = date }; return newArtist; }
private static string UpdateArtist(RequestConsumer reqConsumer, string controller) { Console.Write("Enter id: "); var inputId = int.Parse(Console.ReadLine()); Console.WriteLine("Enter name: "); string name = Console.ReadLine(); Console.WriteLine("Enter country(optional): "); string country = Console.ReadLine(); Console.WriteLine("Enter birth date(optional): "); DateTime? date = null; try { date = DateTime.Parse(Console.ReadLine()); } catch (FormatException ex) { } Artist newArtist = new Artist() { ArtistId = inputId, Name = name, Country = country, DateOfBirth = date }; Console.WriteLine("As Json(1) Or XML(2)? "); string choice = Console.ReadLine(); if (choice == "1") { var sent = reqConsumer.UpdateAsJson<Artist>(newArtist, controller, inputId.ToString()); return sent; } else { var sent = reqConsumer.UpdateAsXML<Artist>(newArtist, controller, inputId.ToString()); return sent; } }
// PUT api/Artist/5 public HttpResponseMessage PutArtist(int id, Artist artist) { // header //User-Agent: Fiddler //Host: localhost:11302 //Content-type: application/json //Content-Length: 91 // request body // { //"ArtistId":"1", //"Name": "Pesho", //"Country": "Somalia", //"DateOfBirth": "1942.01.01" //} if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != artist.ArtistId) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(artist).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }