如何在 ASP.NET Core 控制器方法中支持多种使用 MIME 类型

Reb*_*cca 6 c# asp.net-core

我正在将文件作为流上传,并解决此问题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
    }
}
Run Code Online (Sandbox Code Playgroud)

它仅支持“应用程序/八位字节流”。任何其他(例如“image/jpeg”)都会失败,并显示 415 不支持的媒体类型。

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

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

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

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

Chr*_*jen 6

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

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

    }
Run Code Online (Sandbox Code Playgroud)

发送内容类型为“text/plain”或“text/html”的发布请求有效,而其他内容类型则因 415 不支持的媒体类型而被拒绝。

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

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