我正在使用:
我要做什么
集成测试接受表单数据的API控制器方法。
设置
[FromForm]
属性接受CommandObject的API路由List<IFormFile>
类型,用于管理属于请求的任何文件问题
文件未绑定到List<IFormFile>
属性。其他所有内容均按预期工作,但文件不起作用。这是我第一次使用Multipart Form Data,所以不确定要尝试什么。
当我调试测试时,您可以看到除Documents
属性以外的所有内容都可以正常工作(请注意,这与下面的代码不匹配100%,因为我不得不混淆了一些东西)>
我看过的东西
有很多有关多部分表单数据的内容,我尝试过的一些解决方案是:
MyIntegrationTest.cs
设置集成测试背后有很多代码。如果我将所有内容都张贴在这里,我认为这不会很有帮助。最重要的信息是变量server
的类型为Microsoft.AspNetCore.TestHost.TestServer
[Fact]
async Task Post_ItemAsync_HappyPath_ReturnsOKStatusCode()
{
var fileDir = @"C:/path/to/files";
var fileNames = new string[] { "test.docx", "test.txt" };
using (var server = CreateTestServer())
{
// Arrange
var formData = new MultipartFormDataContent()
{
{ new StringContent("Test Title"), "Title" },
{ new StringContent("Test Description"), "Description" },
{ new StringContent("String_1"), "AListOfStrings" },
{ new StringContent("String_2"), "AListOfStrings" },
{ new StringContent("3"), "NumberOfThings" }
};
foreach (var fileName in fileNames)
{
var document = File.ReadAllBytes($"{fileDir}/{fileName}");
formData.Add(new ByteArrayContent(document), "file", fileName);
}
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
string contentType = "multipart/form-data; boundary=" + formDataBoundary;
var request = new HttpRequestMessage(HttpMethod.Post, "api/v1/item")
{
Headers =
{
{ HttpRequestHeader.ContentType.ToString(), contentType }
},
Content = formData
};
// Act
var response = await server.CreateClient().SendAsync(request);
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Cleanup
...
}
}
MyController.cs
[HttpPost]
ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> CreateItemAsync([FromForm]CreateItemCommand command)
{
bool commandResult = false;
commandResult = await _mediator.Send(command);
if (!commandResult)
{
return BadRequest();
}
return Ok();
}
CreateItemCommand.cs
[DataContract]
public class CreateItemCommand
:IRequest<bool>
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public HashSet<string> AListOfThings { get; set; }
[DataMember]
public int NumberOfThings { get; set; }
[DataMember]
public List<IFormFile> Documents { get; private set; }
public CreateITemCommand()
{
AListOfThings = new HashSet<string>();
}
public CreateItemCommand(string title, string description, HashSet<string> aListOfThings, int NumberOfThings, List<IFormFile> documents)
: this()
{
Title = title;
Description = description;
AListOfStrings = aListOfStrings;
NumberOfThings = numberOfThings;
Documents = documents;
}
}
答案 0 :(得分:1)
表单数据边界应在初始化时添加到MultipartFormDataContent
,并且文件名需要与要填充的模型的所需属性匹配。
//...
// Arrange
string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid());
var formData = new MultipartFormDataContent(formDataBoundary) { //<---- NOTE HERE
{ new StringContent("Test Title"), "Title" },
{ new StringContent("Test Description"), "Description" },
{ new StringContent("String_1"), "AListOfStrings" },
{ new StringContent("String_2"), "AListOfStrings" },
{ new StringContent("3"), "NumberOfThings" }
};
foreach (var fileName in fileNames) {
var document = File.ReadAllBytes($"{fileDir}/{fileName}");
formData.Add(new ByteArrayContent(document), "Documents", fileName); //<-- NOTE HERE
}
// Act
var response = await server.CreateClient().PostAsync("api/v1/item", formData);
//...
需要将模型的Documents
属性设置为公共属性,以便模型绑定程序可以在分析表单数据时填充它。