What is the best way to check if response headers have already been sent or the body has already been written to in .NET?

  • Page Owner: Not Set
  • Last Reviewed: 2024-12-27

Trying to modify the headers after a HttpResponse has started will result in an exception. For example, setting headers and a status code will throw an exception after the response starts. Writing to the response body after it has already been sent may cause a protocol violation, such as writing more than the stated Content-Length or may corrupt the body format, such as writing an HTML footer to a CSS file. What is the best way to avoid these situations in .NET?


Answer

For .NET Core, HttpResponse.HasStarted is a useful hint to indicate if headers have been sent or the body has been written to: https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.httpresponse.hasstarted?view=aspnetcore-9.0

For .NET Framework, HttpResponse.HeadersWritten is the best way to check whether the response headers have been written: https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponse.headerswritten?view=netframework-4.8.1

HttpResponseBase.AddOnSendingHeaders(Action<HttpContextBase>) can also be used in .NET Framework to register a callback that the ASP.NET runtime will invoke immediately before response headers are sent for a request: https://learn.microsoft.com/en-us/dotnet/api/system.web.httpresponsebase.addonsendingheaders?view=netframework-4.8.1