I'm sure somebody had the same problem, but I didn't find anything. I send post request to get the file, and I get this model as a response:
public class ResponseWithFile
{
public bool IsSuccessful { get; set; }
public List<int> Errors { get; set; }
public IFormFile File { get; set; }
}
I get this response from a controller:
[Route("get")]
[HttpPost]
public async Task<IActionResult> GetFile([FromBody]GetFileDto request)
{
var result = _fileService.GetFile(request.Id, request.ContentType);
if (result.IsSuccessful)
return Ok(result);
return BadRequest(result);
}
The response is correct, I can read it into a string, but when I try to deserialize it into response object I get error:
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
string respString = string.Empty;
using (var sr = new StreamReader(resp.GetResponseStream()))
{
respString = sr.ReadToEnd();
}
var serResp = (ResponseWithFile)JsonConvert.DeserializeObject(respString);//error here
InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'ServiceModels.ResponseWithFile
I'm sure it's because of IFormFile object. What am I doing wrong?
Try this:
var serResp = JsonConvert.DeserializeObject<ResponseWithFile>(respString);
or
var serResp = (ResponseWithFile)JsonConvert.DeserializeObject(respString, typeof(ResponseWithFile));