c# - 如何在 ASP.NET Core Controller 方法中支持多个 Consumes MIME 类型

标签 c# asp.net-core

我正在上传一个文件作为流,解决方法是来自 this issueStream 模型绑定(bind),并且我想支持多种 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 的文档状态:

Gets or sets the supported request content types. Used to select an action when there would otherwise be multiple matches.

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

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

最佳答案

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

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

    }

发送内容类型为“text/plain”或“text/html”的 post 请求有效,而其他内容类型被拒绝并返回 415 unsupported media type。

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

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

关于c# - 如何在 ASP.NET Core Controller 方法中支持多个 Consumes MIME 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53434138/

相关文章:

c# - 重写方法文档

c# - Unity 5.3 如何加载当前电平?

c# - Azure Web 应用程序中未找到 Win32 DLL 错误

.net - 如何将库项目中的 ASP.NET Core 3.0 类型用于共享 Controller 、中间件等?

c# - 为 Swagger 的 multipart/form-data 中的文件指定内容类型

c# - 从 Java 迁移到 C#

c# - 在 C# 中,搜索列表中的元素但执行 "StartsWith()"搜索的最快方法是什么?

c# - ASP.NET c# 中的 AJAX 错误

c# - 从 Bot 类外部访问 BotState 变量

c# - ASP.NET Core - DI - 使用 Action<T> 或 IOption<T>