简体   繁体   English

我将 .net5 mvc 项目中的文件列表发送到 .net5 api,但只得到一个文件而不是文件列表

[英]I send list of files from .net5 mvc project to .net5 api, but get only one file instead of the list of files

I have two models as follows:我有两个模型如下:

public class Category
{
  public int Id { get; set; }
  public string Name { get; set; }
  public List<CategoryDetail> CategoryDetails { get; set; }
}


public class CategoryDetail
{
  public int Id { get; set; }
  public string Url { get; set; }
  public IFormFile File { get; set; }
  public Category Category { get; set; }
}

I can bind categorydetail model in .NET5 mvc with list of files.我可以将 .NET5 mvc 中的 categorydetail model 与文件列表绑定。 The problem is, I get only one file when it post to the .NET5 API.问题是,当它发布到 .NET5 API 时,我只得到一个文件。 It seems to me that MultipartFormDataContent cannot bind multiple files when loop through each file.在我看来,MultipartFormDataContent 在遍历每个文件时无法绑定多个文件。

The following code send post request to the API以下代码向 API 发送 post 请求

var multiForm = new MultipartFormDataContent();
multiForm.Add(new StringContent(entity.Id), "Id");
multiForm.Add(new StringContent(Convert.ToString(entity.Name)), "Name");

**foreach (var item in entity.CategoryDetails)
{
  int i = 0;
  multiForm.Add(new StringContent(item.Url), 
 "CategoryDetails[" + i + "].Url");
  multiForm.Add(new StreamContent(item.File.OpenReadStream()), 
 "CategoryDetails[" + i + "].File", item.File.FileName);
  i++;
}**

 var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = multiForm };

 var accessToken = _context.HttpContext.User.Claims.FirstOrDefault(c => 
 c.Type==AppClaims.AccessToken)?.Value;
 if (!string.IsNullOrEmpty(accessToken))
 {
   request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 }

 var client = _clientFactory.CreateClient("ApiServer");
 var response = await client.SendAsync(request).ConfigureAwait(false);

Api Controller Function as follows: Api Controller Function如下:

    [RequestSizeLimit(2147483648)]
    [HttpPost("add")]
    [Consumes(@"application/octet-stream", @"application/x-www-form-urlencoded", "multipart/form-data")]
    [ProducesResponseType(200, Type = typeof(BaseResponse))]

    public async Task<IActionResult> AddCategorySection([FromForm] 
    Category model)
    {
    }

The above code will work correctly.上面的代码将正常工作。 I just wrongly initialize the increment variable inside the foreach loop and each time initialize to 0. The correct code is as follows-我只是错误地在foreach循环中初始化了增量变量,并且每次都初始化为0。正确的代码如下-

int i = 0;
foreach (var item in entity.CategoryDetails)
{
  multiForm.Add(new StringContent(item.Url), 
  "CategoryDetails[" + i + "].Url");
  multiForm.Add(new StreamContent(item.File.OpenReadStream()), 
  "CategoryDetails[" + i + "].File", item.File.FileName);
  i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM