我有一個對 API 進行異步呼叫的方法,API 回傳的資料結構與我要分配的模型相同。但是它從不加載物件。資料始終為空,但如果有來自 API 的回應并且它提供了資料,但沒有將其分配給變數:“播客”
此方法的目的是將資料傳遞給查看。(我在 Web 專案中使用 .Net core 5)
這是我的方法
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);
}
這是我的模型:
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; }
}
uj5u.com熱心網友回復:
如果您的所有回應都具有相同的形狀,則最好創建一個包含您想要的類的通用類
例子:
public class Response<T>
{
public T Data { get; set; }
// additional items like errors and such
}
然后在你的除菌器中你會像這樣使用它
podcast = JsonConvert.DeserializeObject<Response<PPodcast>>(apiResponse).Data;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/327257.html
標籤:C# json 接口 asp.net核心 http客户端
上一篇:更新類中Json屬性的名稱
