[英]I send list of files from .net5 mvc project to .net5 api, but get only one file instead of the list of files
我有兩個模型如下:
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 中的 categorydetail model 與文件列表綁定。 問題是,當它發布到 .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 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)
{
}
上面的代碼將正常工作。 我只是錯誤地在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.