我正在调用API来获取一组作为JSON的赋值数据。我想将其转换为C#模型对象,并在我的MVC视图中显示结果。到目前为止,这是我的代码,成功地将结果带回来,现在我需要将它转换为赋值模型(即我需要API response.content转换为赋值)。
[HttpGet]
public async Task<ViewResult> Index()
{
if (!ModelState.IsValid)
{
return View("Error");
}
HttpRequestMessage apiRequest = CreateRequestToService(HttpMethod.Get, "api/Assignment/GetAll");
HttpResponseMessage apiResponse;
Assignment assignment = new Assignment();
try
{
apiResponse = await HttpClient.SendAsync(apiRequest);
}
catch
{
return View("Error");
}
if (!apiResponse.IsSuccessStatusCode)
{
return View("Error");
}
var result = apiResponse.Content.ReadAsStringAsync();
var results = ???
return View( results);
}
答案 0 :(得分:2)
我需要API response.content转为分配
将响应内容转换为所需类型。让我们假设它是模型的集合
//...
var assignments = await apiResponse.Content.ReadAsAsync<List<Assignment>>();
//...