I've got data from an API, deserializing it to work with my model, but when I try to add that data to my database its only stores a blank object.I've tried passing through CrdResponse but that provides an exception that I can't get around.
public async Task <ActionResult> InsertCard(Card card)
{
List<Card> CardsInfo = new List<Card>();
var getUrl = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
var test = new Uri(getUrl);
var id = test.Segments.Last();
SingleResult += id;
using (var client = new HttpClient())
{
//passing service baseurl
client.BaseAddress = new Uri(SingleResult);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource Getallcards using HTTPClient
HttpResponseMessage Res = await client.GetAsync(SingleResult);
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
//Storing the response details received from web api
var CrdResponse = Res.Content.ReadAsStringAsync().Result;
//Deserializing the response recieved from web api and storing in to the card list
CardsInfo = JsonConvert.DeserializeObject<List<Card>>(CrdResponse);
_context.Cards.Add(card);
_context.SaveChanges();
}
}
return RedirectToAction("Index", "API");
}
and my Model
public class Card
{
public int Id { get; set; }
public string Name { get; set; }
public int? Atk { get; set; }
public int? Def { get; set; }
public string Desc {get; set;}
public int? Level { get; set; }
public string Type { get; set; }
public string Attribute { get; set; }
[DisplayName("Image")]
public IList<Image> Card_Images { get; set; }
public IList<Deck> Deck { get; set; }
}
EDIT: CrdResponse contains:
[{"id":"11714098","name":"30,000-Year White Turtle","type":"Normal Monster","desc":"A huge turtle that has existed for more than 30,000 years.","atk":"1250","def":"2100","level":"5","race":"Aqua","attribute":"WATER","card_images":[{"id":"11714098","image_url":"https://storage.googleapis.com/ygoprodeck.com/pics/11714098.jpg","image_url_small":"https://storage.googleapis.com/ygoprodeck.com/pics_small/11714098.jpg"}],"card_prices":{"cardmarket_price":"0.00","tcgplayer_price":"0.00","ebay_price":"10.0","amazon_price":"0.00"}}]
which is all the info i am hoping to pull through
>(CrdResponse);` is where your erro occurs, try making it as `CardsInfo = JsonConvert.DeserializeObject(CrdResponse);`
– mahlatse Sep 12 '19 at 13:34