我有一個 API 專案,我需要使用 API 開發一個 Web 專案,我撰寫了一些代碼,但無法找到例外和問題,也無法從鏈接中獲取資料。
這是我的服務代碼:
public async Task<IEnumerable<AgentReadDto>> GetAgent()
{
IEnumerable<AgentReadDto> agents = new List<AgentReadDto>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44331/api/");
var response = client.GetAsync("Agent/GetAllAgent");
response.Wait();
var result = response.Result;
if (result.IsSuccessStatusCode)
{
var readTask =JsonConvert.DeserializeObject<IList<AgentReadDto>>(await result.Content.ReadAsStringAsync());
agents = readTask;
}
}
return agents;
}
我的控制器代碼如下所示:
public IActionResult AgentLists()
{
var agentsList = _agentRespositoryWeb.GetAgent();
if (agentsList != null )
{
ViewBag.Message = "There was a problem retrieving agent from the database or no agents exists";
}
ViewBag.SuccessMessage = TempData["SuccessMessage"];
return View(agentsList);
}
我的 api 回傳以下值:
{
"agentDetail": [
{
"usersId": 85,
"firstName": "Amit",
"lastName": "One",
"gender": "Male",
"informationTips": [
{
"video": "https://www.w3schools.com/html/movie.mp4"
},
{
"video": "https://www.w3schools.com/html/movie.mp4"
},
]
},
{
"usersId": 86,
"firstName": "Amit",
"lastName": "Two",
"gender": "Male",
"informationTips": [
{
"video": "https://www.w3schools.com/html/movie.mp4"
}
]
}
]
}
除了我添加的影像之外,有三個影像在不同的步驟中顯示:



uj5u.com熱心網友回復:
您的模型設定為IEnumerable<AgentReadDto>,但您忘記了對操作內部的await呼叫。這意味著視圖期望的 ( ) 和它接收的 ( ) 之間存在不匹配。GetAgentAgentListsIEnumerable<AgentReadDto>Task<IEnumerable<AgentReadDto>>
要解決此問題,請轉換AgentLists為async方法,然后await呼叫GetAgent. 這是該操作的固定版本AgentLists:
public async Task<IActionResult> AgentLists()
{
var agentsList = await _agentRespositoryWeb.GetAgent();
if (agentsList != null)
{
ViewBag.Message =
"There was a problem retrieving agent from the database or no agents exists";
}
ViewBag.SuccessMessage = TempData["SuccessMessage"];
return View(agentsList);
}
看起來您期望回傳的型別與實際回傳的 JSON 之間也存在不匹配。JSON 表示一個物件,其中包含一個串列,但您試圖將其決議為一個簡單的串列。要解決這個問題,請創建一個與回應結構匹配的包裝類。例如,創建以下類:
public class ApiResponse
{
public IEnumerable<AgentReadDto> AgentDetail { get; set; }
}
更新反序列化邏輯以使用這種新型別:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(...);
var agentsLit = apiResponse.AgentDetail;
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422435.html
標籤:
上一篇:LinuxDocker中的CMakeLib缺少依賴項
下一篇:NetCore2.1無法啟動,因為缺少Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation?
