0

I'm creating an WebAPI with C# .netcore. I have a method which gets file stream (different types) from a URL based on file id

function async Task<T> GetFile(string id) {
   HttpRequestMessage request = new HttpRequestMessage();
   request.RequestUri = new Uri("serverURL" + id);
   request.Method = HttpMethod.Get;
   HttpResponseMessage response = await httpClient.SendAsync(request, 
   HttpCompletionOption.ResponseContentRead, cancelToken);
   var result = await response.Content.ReadAsStringAsync();
   return JsonConvert.DeserializeObject<T>(result);
}

I want to return the result into a model like this

public class FileModel
{
    public HttpResponseMessage File { get; set; }
}

I convert the result after that to base64 to get the file.

I get this error Unexpected character encountered while parsing value: B. Path '', line 0, position 0 because JsonConvert cannot convert the result into my FileModel class. I cannot use HttpResponseMessage instead of in the method, the method should be generic.

Thanks

Daina Hodges
  • 823
  • 3
  • 12
  • 37

2 Answers2

0

Have you check, if you Json is in correct format. It seems like, you "result" is not in the correct form.

JsonConvert.DeserializeObject(result) is expecting Proper Json, otherwise it will return error.

  1. To check if the Json structure is proper: http://jsonlint.com/
  2. To generate class from Json structure: https://app.quicktype.io/?l=csharp
  • the result is binary result which looks like this %PDF-1.5 %�쏢 5 0 obj <> stream x��<�r�������J-g�3��V*b,{m+ڍ�J6�@�G�#Z�g?t���=�t�z�����JŪ\�F��?T����N�|��W��]q��������� – Daina Hodges Jul 21 '20 at 16:38
  • Please Visit https://stackoverflow.com/a/24675852/10945191 https://stackoverflow.com/questions/24672900/filestream-response-shows-instead-latin-characters – Bhavesh Patel Jul 21 '20 at 16:45
0

Your FileModel should not have a property of type HttpResponseMessage because that is not what the Json deserializer will return. It will try to convert that JSON into a class based on the generic model (T) you are using. The structure of your generic model (T) must match the JSON that is being returned.

For example, if your json looks like this:

{
 field1: "value1",
 field2: 123
}

Your model should look like this

public class MyModel {
  string field1 { get; set;}
  int field2 { get; set;}
}

If the results of your api calls are different models, then you need to create a new model for each call. You shouldn't try and use the same model for all of your calls.

schwechel
  • 305
  • 3
  • 10