- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用:
[FromForm]
接受 CommandObject 的 API 路由属性 List<IFormFile>
类型。 , 这旨在管理请求中的任何文件 List<IFormFile>
属性(property)。其他一切都按预期工作,但文件没有。这是我第一次使用多部分表单数据,所以不知道该尝试什么。
Documents
之外的一切正常。属性(注意,这与下面的代码不匹配 100%,因为我不得不混淆一些东西)
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
...
}
}
[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();
}
[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;
}
}
最佳答案
表单数据边界应添加到 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
属性需要设置为公共(public),以便模型绑定(bind)器可以在解析表单数据时填充它。
关于具有 FromForm 绑定(bind)到 IFormFile 属性的 C# 集成测试 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56722267/
我有一个物理文件,我想将它传递给需要 IFormFile 类型(用于单元测试)的 Controller 方法。 我找不到任何实例化 IFormFile 接口(interface)的类,这意味着我无法创
我正在开发 ASP.NET Core 2 MVC 应用程序,尝试设置服务层。我有一个非常基本的应用程序,我想在其中: 在姓名旁边上传一张图片 向数据库添加一条记录 将文件存储在磁盘上的 wwwroot
我正在尝试通过 IFormFile 读取一个 zip 文件,我正在浏览里面的文件以解压缩选定的扩展名并解压缩它,但我无法使用IFormFile 来读取它。它说无法将 IFormFile 转换为字符串。
我上传了一张图片并想将它发送到第三方服务(Cloudinary)而不将文件保存在我的服务器中。 public async Task> GetImagesUrlsByImage(IFormFile im
[Route("api/file")] [Produces("application/json")] [Consumes("application/json", "application/json-p
我正在使用 C# 和 Net Core 开发一些 REST API 我的存储库中有一个函数接受类型为 IFormFile 的参数. public async Task UploadFile(IForm
[Route("api/file")] [Produces("application/json")] [Consumes("application/json", "application/json-p
是否可以将 IFormFile 文件添加到 .net core 中的电子邮件附件中?我正在使用 formdata 从 Angular 获取文件。 for (let file of this.file
我有以下代码(我仍在开发它)成功地将文件上传到所需的路径。 private async Task AddImage(IFormFile image, string filePath) {
我正在尝试使用 this piece of code 将文件保存在磁盘上. IHostingEnvironment _hostingEnvironment; public ProfileControl
我正在尝试阅读 IFormFile从这样的 HTTP POST 请求中收到: public async Task UploadDocument([FromForm]DataWrapper data)
我正在尝试使用 IFormFile 作为嵌套 ViewModel 中的属性。我在尝试将 ViewModel 绑定(bind)到运行时的 Controller 操作时遇到问题。 AJAX 请求停止并且永
我有一个 .NET Core API 项目,它有一个简单的端点来上传文件: [Route("api/[controller]")] [ApiController] public class Files
我有一个 .NET Core API 项目,它有一个简单的端点来上传文件: [Route("api/[controller]")] [ApiController] public class Files
我的 WebAPI 方法已准备好接受文件作为参数,如下所示:(例如 URI“https://localhost:44397/api/uploadfile” [Route("api/[controll
我用这段代码改变了图像的大小。但此方法返回 FileStreamResult。我想将 FileStreamResult 转换为 IFromFile。我该怎么做? 注意:我正在使用 CoreCompat
在 ASP.Net Core Web API 中为我的一个服务类编写单元测试时,我需要模拟一个 IFormFile。因此我决定像这样模拟它(使用最小起订量): fileMock.Setup(x =>
我有一个 .NET Core 应用程序,它有一个名为 Documents 的 Controller ,带有一个 POST 签名,如下所示: [HttpPost] public async Task P
我正在制作一个可以上传到数据库和从数据库检索图像的 API。第一部分已完成 - 图像存储在 IFormFile 变量中,并作为 bytes[] 传递给数据库。 图片模型: public class I
我有后端端点 Task Post(IFormFile csvFile)我需要从 HttpClient 调用这个端点。目前我得到 Unsupported media type error .这是我的代码
我是一名优秀的程序员,十分优秀!