The following code does not get compiled and unfortunately I could not figure out why.
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.MapPost("/multi", async (ctx) =>
{
Console.WriteLine("HTTP headers");
Console.WriteLine(ctx.Request.Headers.ContentType);
Console.WriteLine("??????????????????????????????????????");
Console.WriteLine("HTTP body");
string? line;
ctx.Response.StatusCode = StatusCodes.Status201Created;
var ms = new MemoryStream();
await ctx.Request.Body.CopyToAsync(ms);
using (StreamReader stream = new StreamReader(ms))
{
await stream.ReadToEndAsync()
.ContinueWith(async t =>
{
var b = await t;
Console.WriteLine(b);
});
}
Console.WriteLine("??????????????????????????????????????");
Console.WriteLine("FORM data");
foreach (var form in ctx.Request.Form)
{
Console.WriteLine("Key: {0} => Value: {1}", form.Key, form.Value);
}
return await ctx.Response.WriteAsync("Hello");
});
app.Run("http://localhost:8080");
The compiler complains:
[{
"resource": "/c:/5_.netcore/multipart/Program.cs",
"owner": "msCompile",
"code": "CS8031",
"severity": 8,
"message": "Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task<T>'? [C:\\5_.netcore",
"startLineNumber": 34,
"startColumn": 5,
"endLineNumber": 34,
"endColumn": 5
}]
What am I doing wrong?
CodePudding user response:
You are returning a Task<T>
at return await ctx.Response.WriteAsync("Hello");
the compiler wants that you return a Task
.
You should do:
await ctx.Response.WriteAsync("Hello");
return;