From c3085c6c985eb513d2152acf9b440f8b7381d9f0 Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Thu, 16 Dec 2021 11:25:08 +1300 Subject: [PATCH] Add minimal API sample of reading the request stream (#24327) Co-authored-by: Luke Latham <1622880+guardrex@users.noreply.github.com> Co-authored-by: Stephen Halter --- aspnetcore/fundamentals/minimal-apis.md | 11 +++++++++++ .../minimal-apis/samples/WebMinAPIs/Program.cs | 16 ++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/aspnetcore/fundamentals/minimal-apis.md b/aspnetcore/fundamentals/minimal-apis.md index a711bc707f..97c6a7f204 100644 --- a/aspnetcore/fundamentals/minimal-apis.md +++ b/aspnetcore/fundamentals/minimal-apis.md @@ -597,6 +597,17 @@ The preceding code: } ``` +### Read the request body + +Read the request body directly using a or parameter: + +[!code-csharp[](minimal-apis/samples/WebMinAPIs/Program.cs?name=snippet_fileupload)] + +The preceding code: + +* Accesses the request body using . +* Copies the request body to a local file. + ## Responses Route handlers support the following types of return values: diff --git a/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs b/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs index 73679f9b40..92af794a75 100644 --- a/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs +++ b/aspnetcore/fundamentals/minimal-apis/samples/WebMinAPIs/Program.cs @@ -813,4 +813,20 @@ app.MapGet("/skipme", () => "Skipping Swagger.") app.Run(); #endregion +#elif FILEUPLOAD +#region snippet_fileupload +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapPost("/uploadstream", async (IConfiguration config, HttpRequest request) => +{ + var filePath = Path.Combine(config["StoredFilesPath"], Path.GetRandomFileName()); + + await using var writeStream = File.Create(filePath); + await request.BodyReader.CopyToAsync(writeStream); +}); + +app.Run(); +#endregion + #endif \ No newline at end of file