【问题标题】:How to support multiple Consumes MIME Types in ASP.NET Core controller method如何在 ASP.NET Core 控制器方法中支持多种使用 MIME 类型
【发布时间】:2018-11-22 15:28:55
【问题描述】:

我正在将文件作为流上传,并使用来自this issueStream 模型绑定的解决方法,并且我想支持多种 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 而失败。

我无法添加多个ConsumeAttributesConsumeAttribute.ContentTypes 的文档指出:

获取或设置支持的请求内容类型。用于选择一个 否则会有多个匹配项时的操作。

我不知道该文档试图说明什么,但我认为这是支持额外 MIME 类型的一种方式!有什么办法可以支持多种 MIME 类型?

更新 这里的方法签名是固定的,不能更改。 ConsumesAttribute 用于生成 Swagger JSON 文件,客户端使用该文件为该 API 生成自己的多平台客户端。

【问题讨论】:

  • 我想知道IFormFile 是否可以解决这个问题,
  • 这是从 http 客户端直接上传文件。我们不想使用 IFormFile,因为它对于非浏览器客户端来说绝对是一件痛苦的事情。我们只想流式传输 body 并完成它。 MultipartFormDataContent 对于简单的文件上传来说是可怕的。仍然Consumes 必须能够支持multipel 选项。我只是不知道怎么做。
  • 我们能否将流转换为IFormFile,然后验证ContentType 属性?
  • 我正在使用 ConsumesAttribute 进行 Swagger 生成(与客户端共享,因此这里的接口是固定的)。没有它,Consums 部分不会生成,并且生成的 Swagger 客户端不知道要支持哪些媒体类型。消费应该支持多个选项,文档建议支持,但事实并非如此。

标签: c# asp.net-core


【解决方案1】:

您的 Consumes 属性是正确的。我用 dotnet core 2.1 对其进行了测试,它按预期工作:

    [HttpPost("test")]
    [Consumes("text/plain", new[] { "text/html" })]
    public void Test()
    {

    }

使用 Content-Type "text/plain" 或 "text/html" 发送 post 请求有效,而其他内容类型因 415 不受支持的媒体类型而被拒绝。

但是:如果我添加 [FromBody] 流文件,它将停止工作。

 // Does NOT work:
 [Consumes("text/plain", new[] { "text/html" })]
 public void Test([FromBody] Stream file)

【讨论】:

  • 我也测试过。正如我在问题顶部指出的那样,我正在使用以下解决方法解决流问题:stackoverflow.com/questions/41346128/… 问题就在那里。在 CanRead 方法中!通过将我的额外 mime 类型添加到该方法中解决了问题。没有更多的 415!
  • var stream = Request.Body; 有问题吗? ?
  • 更改 StreamInputFormatter 解决了问题!所有其他内容类型的 415 是由行 if (contentType == "application/octet-stream") { return true; } 引起的。谢谢你帮助我证明它应该工作!
  • 酷 - 我担心我必须阅读 StreamInputFormatter ;-)
猜你喜欢
  • 2011-05-23
  • 2020-05-05
  • 1970-01-01
  • 2021-01-11
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-07-27
  • 1970-01-01
相关资源
最近更新 更多