1

I have problem with WriteAsync method in asp.net core.

I have code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

app.Use(async (HttpContext context, RequestDelegate next) =>
{
    await context.Response.WriteAsync("Hello again");
    await next(context);
});

app.Run();

It runs into following error:

fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
      System.InvalidOperationException: StatusCode cannot be set because the response has already started.
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ThrowResponseAlreadyStartedException(String value)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Builder.ApplicationBuilder.<>c.<Build>b__18_0(HttpContext context)
         at Program.<>c.<<<Main>$>b__0_1>d.MoveNext() in C:\aspnetApps\WebApplication_test\WebApplication_test\Program.cs:line 13
      --- End of stack trace from previous location ---
         at Program.<>c.<<<Main>$>b__0_0>d.MoveNext() in C:\aspnetApps\WebApplication_test\WebApplication_test\Program.cs:line 7
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
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 "0HMN0TEI6NPN9", Request id "0HMN0TEI6NPN9:00000002": 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)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.Microsoft.AspNetCore.Http.Features.IHttpResponseFeature.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Http.DefaultHttpResponse.set_StatusCode(Int32 value)
         at Microsoft.AspNetCore.Builder.ApplicationBuilder.<>c.<Build>b__18_0(HttpContext context)
         at Program.<>c.<<<Main>$>b__0_1>d.MoveNext() in C:\aspnetApps\WebApplication_test\WebApplication_test\Program.cs:line 13
      --- End of stack trace from previous location ---
         at Program.<>c.<<<Main>$>b__0_0>d.MoveNext() in C:\aspnetApps\WebApplication_test\WebApplication_test\Program.cs:line 7
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
         at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
         at Microsoft.WebTools.BrowserLink.Net.BrowserLinkMiddleware.ExecuteWithFilterAsync(IHttpSocketAdapter injectScriptSocket, String requestId, HttpContext httpContext)
         at Microsoft.AspNetCore.Watch.BrowserRefresh.BrowserRefreshMiddleware.InvokeAsync(HttpContext context)
         at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)

If i add tags to hello messages, the app runs correctly. Like this:

await context.Response.WriteAsync("<p>Hello</p>");

If i change content-type to 'text/plain' it runs into the same error. Like this:

app.Use(async (HttpContext context, RequestDelegate next) =>
{
    context.Response.ContentType = "text/plain";
    await context.Response.WriteAsync("Hello");
    await next(context);
});

I have no idea why is it working like this. I`d like to reply by plain text.

Julian
  • 33,915
  • 22
  • 119
  • 174
Fatman54
  • 11
  • 2
  • [Please do not upload images of errors](https://meta.stackoverflow.com/q/285551) but provide it as text – Klaus Gütter Dec 18 '22 at 11:41
  • ok. I provided it as text – Fatman54 Dec 18 '22 at 11:50
  • Middleware don't compose well like that. Only one middleware should produce a response. Middleware should not call `next` after starting the response. This exception happens because next reached the end of the pipeline and hit the default 404 handler, but the status code couldn't be changed because the response had already started. – Tratcher Dec 19 '22 at 17:47

0 Answers0