// POST api/Song public HttpResponseMessage PostSong(Song song) { // header //User-Agent: Fiddler //Host: localhost:11302 //Content-type: application/json //Content-Length: 86 // req body //{ //"Title": "Example Song", //"Year": "2001.06.16", //"Genre": "Suicidal Death Metal" //} if (ModelState.IsValid) { db.Songs.Add(song); db.SaveChanges(); HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, song); response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = song.SongId })); return response; } else { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }
private static string UpdateSong(RequestConsumer reqConsumer, string controller) { Console.Write("Enter id: "); var inputId = int.Parse(Console.ReadLine()); Console.WriteLine("Enter title: "); string title = Console.ReadLine(); Console.WriteLine("Enter genre(optional): "); string genre = Console.ReadLine(); Console.WriteLine("Enter release date(optional): "); DateTime? releaseDate = null; try { releaseDate = DateTime.Parse(Console.ReadLine()); } catch (FormatException ex) { } MusicStoreContext db = new MusicStoreContext(); Console.WriteLine("Artist Name(optional): "); string artistName = Console.ReadLine(); var artist = (Artist)(from a in db.Artists where a.Name == artistName select a ).FirstOrDefault(); Song newSong; if (artist == null) { newSong = new Song() { SongId = inputId, Title = title, Genre = genre, Year = releaseDate }; } else { newSong = new Song() { SongId = inputId, Title = title, Genre = genre, Year = releaseDate, Artist = CreateArtistObject(artist.ArtistId, artist.Name, artist.Country, artist.DateOfBirth) }; } Console.WriteLine("As Json(1) Or XML(2)? "); string choice = Console.ReadLine(); if (choice == "1") { var sent = reqConsumer.UpdateAsJson<Song>(newSong, controller, inputId.ToString()); return sent; } else { var sent = reqConsumer.UpdateAsXML<Song>(newSong, controller, inputId.ToString()); return sent; } }
// PUT api/Song/5 public HttpResponseMessage PutSong(int id, Song song) { // header //User-Agent: Fiddler //Host: localhost:11302 //Content-type: application/json //Content-Length: 101 // req body //{ //"SongId": "1", //"Title": "Edited song", //"Year": "2001.06.16", //"Genre": "Suicidal Death Metal" //} if (!ModelState.IsValid) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } if (id != song.SongId) { return Request.CreateResponse(HttpStatusCode.BadRequest); } db.Entry(song).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException ex) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex); } return Request.CreateResponse(HttpStatusCode.OK); }