Expires header set to '-1' automatically when writing to HttpResponse.Body in IExceptionHandler.TryHandleAsync() method.
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 281
Description
### Is there an existing issue for this?
- [x] I have searched the existing issues
### Describe the bug
I created an implementation of the `IExceptionHandler` to write a custom error when an unhandled exception is occured in an action method of a controller:
```csharp
public class CustomExceptionHandler : IExceptionHandler
{
public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
await httpContext.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("The error"));
return true;
}
}
```
After calling the `httpContext.Response.Body.WriteAsync()` the header `Expires` is automatically added with the `-1` value.
### Expected Behavior
After calling `httpContext.Response.Body.WriteAsync()` no `Expires` header should be added. Specially with the `-1` value which is not a standard value for an "http-date" (See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires).
### Steps To Reproduce
To reproduce the error:
- Create an implementation of the `IExceptionHandler` interface which write simple UTF-8 encoding string.
```csharp
public class CustomExceptionHandler : IExceptionHandler
{
public async ValueTask TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
await httpContext.Response.Body.WriteAsync(Encoding.UTF8.GetBytes("The error"));
return true;
}
}
```
- Register the `CustomExceptionHandler` in the `Main()` entry point using the `AddExceptionHandler()` extension method.
- Add the `UseExceptionHandler()` middleware in pipeline execution.
- Throws an exception is an action controller.
```csharp
[HttpGet(Name = "GetWeatherForecast")]
public string Get()
{
throw new DivideByZeroException("The exception !");
}
```
Run the application and execute the action on a browser. When the action is called, the `CustomExceptionHandler` is called, the `The error` message is returned as response of the HTTP query, but the header `Expires` is automatically added with the `-1` value.
I created a simple project to reproduce the issue and available here [aspnetcore.ExceptionHandlerExpiresHeaderBug](https://github.com/GillesTourreau/aspnetcore.ExceptionHandlerExpiresHeaderBug).
- Just open the `ExceptionHandlerExpiresHeaderBug`.
- Run the application.
- Look at the response of the call of the HTTP page with the developer tools of the browser:

### Exceptions (if any)
_No response_
### .NET Version
8.0.403
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.