c# 如何反序列化 IFormFile

c# how to deserialize IFormFile

我确定有人遇到了同样的问题,但我什么也没找到。 我发送 post 请求来获取文件,我得到这个模型作为响应:

    public class ResponseWithFile
{
    public bool IsSuccessful { get; set; }
    public List<int> Errors { get; set; }
    public IFormFile File { get; set; }
}

我从管理员那里得到了这样的回复:

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

响应是正确的,我可以将它读入一个字符串,但是当我尝试将它反序列化为响应对象时出现错误:

            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

我确定这是因为 IFormFile 对象。我做错了什么?

试试这个:

var serResp = JsonConvert.DeserializeObject<ResponseWithFile>(respString);

  var serResp = (ResponseWithFile)JsonConvert.DeserializeObject(respString, typeof(ResponseWithFile));