我有以下两种型号:
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; }
}
我可以绑定分类详细模型。NET5 mvc文件列表。问题是,我得到只有一个文件时,它张贴到。NET5 API.在我看来,MultipartFormDataContent在循环遍历每个文件时无法绑定多个文件。
下面的代码向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控制器功能如下:
[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)
{
}
以上代码将正常工作。我只是错误地初始化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++;
}