'Error on adding code in app.run() function in the program.cs file in .net 6 core

I'm trying to convert a console app into a .net6 core Web Api app and for that, I made some changes in the program.cs file too. Everything goes perfectly but when I try to print our a line using:

await context.Response.WriteAsync("string");

I get an error in the .exe window that pops up.

warn: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[2] The response has already started, the error page middleware will not be executed. fail: Microsoft.AspNetCore.Server.Kestrel[13] Connection id "0HMGA3IKGSA02", Request id "0HMGA3IKGSA02:00000001": An unhandled exception was thrown by the application. System.InvalidOperationException: StatusCode cannot be set because the response has already started. at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)

This is the entire code I have written in the program.cs file:

var builder = WebApplication.CreateBuilder(args); // Add services to the container.

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Use(async (context, next) =>
{
    await context.Response.WriteAsync("Hell");
    await next();
});

app.Run();

I'm using Visual Studio 2022.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source