I have a method that makes an asynchronous call to an API, the structure of the data that the API returns is identical to the model I want to assign. However it never loads the object. The data is always null, but if there is a response from the API and if it delivers the data, but does not assign it to the variable: podcast
.
The purpose of this method is to pass the data to view. (I use .Net core 5 in a Web Project)
this is my method
public async Task<IActionResult> details(int id)
{
if (id != 0)
{
//Read Service for config Metas
PPodcast podcast = new PPodcast();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync($"{_storageOption.devVirtualPath}{_endpoints.ObtenerPodcast}" + id))
{
string apiResponse = await response.Content.ReadAsStringAsync();
podcast = JsonConvert.DeserializeObject<PPodcast>(apiResponse);
}
}
ViewBag.idPodcast = id;
return View(podcast);
}
return View(null);
}
This is my model:
public class PPodcast
{
public int id { get; set; }
public int idSeccion { get; set; }
public string titulo { get; set; }
public string descripcion { get; set; }
public string contenido { get; set; }
public string embeb { get; set; }
public string imagenRef { get; set; }
public string tags { get; set; }
public string fecha_PE { get; set; }
public DateTime Fecha { get; set; }
public string Hora { get; set; }
public string urlPodcast { get; set; }
public string SeccionNombre { get; set; }
}
if all of your responses have the same shape, it is better to create a generic class that contains the classes you want
example:
public class Response<T>
{
public T Data { get; set; }
// additional items like errors and such
}
then in your deserilizer you would use it as such
podcast = JsonConvert.DeserializeObject<Response<PPodcast>>(apiResponse).Data;