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

Tom*_*son 12 .net asp.net asp.net-core .net-6.0 minimal-apis

我想在 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);

Run Code Online (Sandbox Code Playgroud)

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

期望支持 JSON 媒体类型,但得到“multipart/form-data; ...

当我说端点应该接受时,不知道为什么它期望支持的 json multipart/form-data

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

Gur*_*ron 14

目前,对最小 API 中的绑定的开箱即用支持相当有限。支持的绑定源:

  • 路线值
  • 请求参数
  • 标头
  • 正文(JSON 形式)
  • 依赖注入提供的服务
  • 风俗

注意:.NET 6 本身不支持表单绑定

您可以利用自定义绑定或使用特殊类型处理

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

UPD

起,最小 API应该能够 直接绑定IFormFile/ :IFormFileCollection

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


Tal*_*ues 9

请注意,您可以上传具有任何ContentType 的文件,如以下示例代码。

在此示例中,我选择了text/plainContentType,但您可以通过将行编辑为所需的 ContentType 来选择自己的 ContentType .Accepts<IFormFile>("text/plain");

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");
Run Code Online (Sandbox Code Playgroud)

Swagger UI 也很好地支持它:

在此输入图像描述