【发布时间】:2018-11-22 15:28:55
【问题描述】:
我正在将文件作为流上传,并使用来自this issue 的Stream 模型绑定的解决方法,并且我想支持多种 MIME 类型的消耗。我认为这会起作用,但它没有:
public class FileController : BaseController
{
[HttpPost("customer/{customerId}/file", Name = "UploadFile")]
[SwaggerResponse(StatusCodes.Status201Created, typeof(UploadFileResponse))]
[Consumes("application/octet-stream", new string[] { "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif"})]
//[Consumes("application/octet-stream", "application/pdf", "image/jpg", "image/jpeg", "image/png", "image/tiff", "image/tif")] // doesn't work either
public async Task<IActionResult> UploadFile([FromBody] Stream file, [FromRoute] string customerId, [FromQuery] FileQueryParameters queryParameters)
{
// file processing here
}
}
它只支持“application/octet-stream”。任何其他诸如“image/jpeg”之类的都因 415 Unsupported Media Type 而失败。
我无法添加多个ConsumeAttributes。 ConsumeAttribute.ContentTypes 的文档指出:
获取或设置支持的请求内容类型。用于选择一个 否则会有多个匹配项时的操作。
我不知道该文档试图说明什么,但我认为这是支持额外 MIME 类型的一种方式!有什么办法可以支持多种 MIME 类型?
更新 这里的方法签名是固定的,不能更改。 ConsumesAttribute 用于生成 Swagger JSON 文件,客户端使用该文件为该 API 生成自己的多平台客户端。
【问题讨论】:
-
我想知道
IFormFile是否可以解决这个问题, -
这是从 http 客户端直接上传文件。我们不想使用 IFormFile,因为它对于非浏览器客户端来说绝对是一件痛苦的事情。我们只想流式传输 body 并完成它。 MultipartFormDataContent 对于简单的文件上传来说是可怕的。仍然Consumes 必须能够支持multipel 选项。我只是不知道怎么做。
-
我们能否将流转换为
IFormFile,然后验证ContentType属性? -
我正在使用 ConsumesAttribute 进行 Swagger 生成(与客户端共享,因此这里的接口是固定的)。没有它,Consums 部分不会生成,并且生成的 Swagger 客户端不知道要支持哪些媒体类型。消费应该支持多个选项,文档建议支持,但事实并非如此。
标签: c# asp.net-core