如何使用 ASP.NET Core 6 minimal api 上传文件?

How do I do file upload using ASP.NET Core 6 minimal api?

我想在 ASP.NET Core 6 中创建一个简单的文件上传端点,我认为它会像这里描述的那样简单 https://dotnetthoughts.net/handling-file-uploads-in-openapi-with-aspnet-core/

当我定义了一个端点时:

app.MapPost("/upload", (IFormFile file) =>
{
    //Do something with the file
    return Results.Ok();
}).Accepts<IFormFile>("multipart/form-data").Produces(200);

当我呼叫终结点时,我收到 415 回复。我收到的消息是这样的:

Expected a supported JSON media type but got "multipart/form-data; ...

当我说端点应该接受 multipart/form-data.

时,不确定为什么它期望支持 json

关于在这里做什么有什么想法或想法吗?

目前对 Minimal API 中绑定的开箱即用支持是 quite limited。支持的绑定源:

  • Route values
  • Query string
  • Header
  • Body (as JSON)
  • Services provided by dependency injection
  • Custom

NOTE: Binding from forms is not natively supported in .NET 6

您可以利用自定义绑定或使用 special types handling:

app.MapPost("/upload", (HttpRequest request) =>
{
    //Do something with the file
    var files = request.Form.Files;
    return Results.Ok();
})
.Accepts("multipart/form-data")
.Produces(200);

这里需要注意的是,您可以像下面的示例代码一样上传具有 any ContentType 的文件。

In this example I chose a text/plain ContentType, but you can choose your own by editing the .Accepts<IFormFile>("text/plain"); line to your desired ContentType.

app.MapPost("/upload",
    async (HttpRequest request) =>
    {
        using (var reader = new StreamReader(request.Body, System.Text.Encoding.UTF8))
        {

            // Read the raw file as a `string`.
            string fileContent = await reader.ReadToEndAsync();

            // Do something with `fileContent`...
    
            return "File Was Processed Sucessfully!";
        }
    }).Accepts<IFormFile>("text/plain");

Swagger也很好的支持UI: