Конечная точка /import должна брать несколько файлов из TestFiles папка:
Код: Выделить всё
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapPost("/import", Import).DisableAntiforgery();
static async Task Import([FromForm] List xyz)
{
if (xyz == null || xyz.Count == 0)
{
return Results.BadRequest("No files were provided.");
}
// This is never reached !!!
return Results.Ok();
}
app.Run();
Код: Выделить всё
using Microsoft.AspNetCore.Mvc.Testing;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
namespace Importer.Tests
{
public class IntegrationTests(WebApplicationFactory
factory) : IClassFixture
{
private readonly WebApplicationFactory _factory = factory;
private readonly string _testFilesPath = Path.Combine(Environment.CurrentDirectory, "TestFiles");
private MultipartFormDataContent CreateMultipartFormDataFromTestFiles(List fileNames)
{
var formContent = new MultipartFormDataContent();
foreach (var fileName in fileNames)
{
string filepath = Path.Combine(_testFilesPath, fileName);
var fileBytes = File.ReadAllBytes(filepath);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
formContent.Add(fileContent, "xyz", fileName);
// "files" parameter name should be the same as the server side input parameter name
//https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-8.0#match-name-attribute-value-to-parameter-name-of-post-method
}
return formContent;
}
[Fact]
public async Task API_Import_File_Should_Return_Http_Status_OK()
{
List fileList = new List { "Input.txt" };
var form = CreateMultipartFormDataFromTestFiles(fileList);
using var client = _factory.CreateClient();
var response = await client.PostAsync("/import", form);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
}
Если тег [FromForm] удален, ответ будет :
Код состояния: 415, ReasonPhrase: «Неподдерживаемый тип носителя»
Если конечная точка /import изменена для обработки только одного файла => IFormFile, все работает!
Любые предложения более чем приветствуются. Спасибо
Подробнее здесь: https://stackoverflow.com/questions/791 ... ts-in-null