我有一个如下所示的 API 方法:
[HttpGet("top/{max}", Name = "GetTopLocations")]
public ActionResult<List<LocationDto>> GetTop(int max)
{
return _locationService.Get();
}
然后我通过 Swagger 使用 NSwag 生成了客户端代码类。我在 Blazor WebAssembly 代码中这样调用此方法:
Locations = await MyProject.Client.GetTopLocationsAsync(10);
但是,这会产生一个异常:
Error: 0 : Could not deserialize the response body stream as System.Collections.Generic.ICollection`1[[MyProject.LocationDto, MyProject.Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
但是如果我在我的浏览器中这样调用这个方法:http://localhost:50464/api/Locations/top/10 然后获取该 JSON 字符串并像这样对其进行反序列化测试:
string jsonStringCopiedFromBrowser = "...";
var thisWorks = JsonConvert.DeserializeObject<ICollection<LocationDto>>(jsonStringCopiedFromBrowser);
我不明白为什么当我像在最后的代码中那样反序列化它而不是从 NSwag 中反序列化时它有效?关于我做错了什么的任何提示?我根本没有修改 NSwag 生成的代码,它直接取自生成的输出。
最佳答案
NSwag Studio 不支持此类操作。 所以你需要手动创建一个列表。 我尝试它的工作 这是下面的代码
public class Response<T>
{
public string Message { get; set; }
public string ValidatonError { get; set; }
public bool Success { get; set; }
public T Data { get; set; }
public IList<T> DataEnum { get; set; }
}
public async Task<Response<EmployeeDetailDTO>> GetEmployee(int ID)
{
Response<EmployeeDetailDTO> response;
try
{
var data = await client.EmployeeAllAsync(ID);
response = new Response<EmployeeDetailDTO>
{
DataEnum = data.ToList(),
Success = true
};
}
catch (ApiException e)
{
response = ConvertApiException<EmployeeDTO>(e);
}
return response;
}
现在在您的客户页面上提取结果
@foreach(var model in rl.ToArray())
{
<td>@model.Complaintname</td>
}
几个小时后,我用这个方法解决了这个问题。如果您发送单个记录,NSwag Studio 会工作。
关于c# - 在 NSwag 生成的代码中从 WebApi 反序列化数据的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63075960/