Problem with Deserializing data from WebApi in NSwag generated code

Viewed 1289

I have an API method that looks like this:

[HttpGet("top/{max}", Name = "GetTopLocations")]
public ActionResult<List<LocationDto>> GetTop(int max)
{
    return _locationService.Get();
}

I have then generated client code class with NSwag via Swagger. I call this method in my Blazor WebAssembly code like this:

Locations = await MyProject.Client.GetTopLocationsAsync(10);

However, this generates an exception:



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]].

But if I call this method in my browser like this: http://localhost:50464/api/Locations/top/10 and then take that JSON string and test to Deserialize it like this:

string jsonStringCopiedFromBrowser = "...";
var thisWorks = JsonConvert.DeserializeObject<ICollection<LocationDto>>(jsonStringCopiedFromBrowser);

I cannot understand why it works when I deserialize it like in the last code but not from NSwag? Any tips on what I am doing wrong? I have not modified the NSwag generated code at all, its taken directly from the generated output.

1 Answers

NSwag Studio does not help with this kind of operation. so you need to create a List mannunally. I try and its work here is the code below

 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;
    }

Now extract the result on your Client Page

 @foreach(var model in rl.ToArray())
         {
          <td>@model.Complaintname</td>
         }

after a couple of hours, I use this method for solving the problem. NSwag Studio work if you send a single Record.

Related