【问题标题】:Send IFormFile To API using HttpClient Alwyes Null ASP.net Core2.2使用 HttpClient Alwyes Null ASP.net Core2.2 将 IFormFile 发送到 API
【发布时间】:2019-03-13 07:56:12
【问题描述】:

我为附件创建了 API 它应该接收带有文件的模型信息 如果我发送文件模型为空如果我没有发送文件模型数据显示

型号

public class AttachmentFilesViewModel
{
    public long Id { get; set; }
    public string FileName { get; set; }

    public string FileExt { get; set; }
    public IFormFile files { get; set; }
    public AttachmentViewModel AttachmentViewModel {get;set; }

}

模型 2

 public class AttachmentViewModel
{
    public long Id { get; set; }
    public string Type { get; set; }


    public long TypeID { get; set; }
    public string FileDesc { get; set; }
    public List<AttachmentFilesViewModel> attachmentFiles {get;set; }

}

控制器从视图中获取文件正确 在这里,我从文件中构建了我的 Viewmodel 文件是正确的

  [HttpPost]
    public async Task<IActionResult> Create(AttachmentViewModel attachment, IFormFile[] Files)
    {

        LawyerAPI lawyerAPI = new LawyerAPI();
        HttpClient httpClient = lawyerAPI.InitializeClient();
        if (Files != null && Files.Count() > 0)
        {
            attachment.attachmentFiles = new List<AttachmentFilesViewModel>();
            foreach (var item in Files)
            {
                AttachmentFilesViewModel att = new AttachmentFilesViewModel();


                att.FileExt = Path.GetExtension(item.FileName);
                att.FileName = item.FileName;
                att.files = item;
                attachment.attachmentFiles.Add(att);
            }

        }

        HttpResponseMessage res = await httpClient.PostAsJsonAsync("api/nofactory/createattachment", attachment);
        List<AttachmentViewModel> model = new List<AttachmentViewModel>();
        model.Add(attachment);
        return View("index", model);

    }

我也试过手动序列化

如果我将文件添加到模型中,这里的 API 我会收到 null 如果我评论上面的 foreach 并且文件列表为空 我收到正确的型号 我也试过 [FromBody]

  [Route("createattachment")]
    // POST api/values
    public IActionResult Post([FromForm] AttachmentViewModel attachment)
    {}

如何将文件获取到 API 谢谢

编辑

查看代码

  @using (Html.BeginForm(null, null, FormMethod.Post, new { @id ="frmAddAttachment" ,enctype="multipart/form-data"})){@Html.HiddenFor(model => model.Type)@Html.HiddenFor(model => model.TypeID)<div class="row">
<div class="card">       
    <div class="card-content">
        <div class="form-horizontal">
            <div class="col-md-10 col-sm-12 col-xs-12">
                <div class="form-group">
                    @Html.TextBoxFor(b => b.FileDesc})
                </div>
            </div>
            <div class="col-md-10 col-sm-12 col-xs-12">
                <input type="file" name="Files" multiple="multiple" />                   
                <button type="submit" class="btn btn-success"> Save</button>
            </div>
        </div>           
    </div>
</div>

我觉得风景还可以 我确实在控制器中获取了文件,但是将它们发送到 API 时出现问题

【问题讨论】:

  • 视图是什么样的?
  • 我已经添加了视图的代码,但我确实从视图中获取了正确的文件,但我无法将它们发送到 API

标签: c# asp.net-core


【解决方案1】:

使用MultipartFormDataContent通过HttpClient发送文件

[HttpPost]
public async Task<IActionResult> Create([FromForm]AttachmentViewModel attachment, [FromForm]IFormFile[] Files)
{
    //initialize attachmentFiles 

    var content = new MultipartFormDataContent();
    content.Add(new StringContent(attachment.Id.ToString()), "Id");
    content.Add(new StringContent(attachment.Type), "Type");
    content.Add(new StringContent(attachment.TypeID.ToString()), "TypeID");
    content.Add(new StringContent(attachment.FileDesc), "FileDesc");
    for (int i = 0; i < attachment.AttachmentFiles.Count; i++)
    {
        var attachmentFile = attachment.AttachmentFiles[i];

        content.Add(new StreamContent(attachmentFile.Files.OpenReadStream()), $"AttachmentFiles[{i}].Files", attachmentFile.Files.FileName);
        content.Add(new StringContent(attachmentFile.FileExt), $"AttachmentFiles[{i}].FileExt");
        content.Add(new StringContent(attachmentFile.FileName), $"AttachmentFiles[{i}].FileName");
        content.Add(new StringContent(attachmentFile.Id.ToString()), $"AttachmentFiles[{i}].Id");
    }


    HttpResponseMessage res = await httpClient.PostAsync("api/nofactory/createattachment", content);
    List<AttachmentViewModel> model = new List<AttachmentViewModel>();
    model.Add(attachment);
    return View("index", model);

}

【讨论】:

  • IOException:无法从传输连接读取数据:I/O 操作已因线程退出或应用程序请求而中止。就行 HttpResponseMessage res = await httpClient.PostAsync("api/nofactory/createattachment", content);如果我传递附件而不是内容它可以工作但仍然为空
  • @MaherKhalil 很难说有什么问题。我测试了这段代码,它运行良好。尝试不传递文件、1 个文件和多个文件,看看会发生什么
  • @MaherKhalil 您的文件名称必须与您的 Post 方法参数的名称相同,在您的情况下,名称必须是:附件。我遇到了同样的问题,在寻找解决方案时我发现了这个很棒的提示:makolyte.com/aspnetcore-receive-a-file-in-the-request。可能您找到了一些解决方案,但它可能对其他人有用
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多