简体   繁体   中英

System.ObjectDisposedException when writing into HttpContext

I made custom exception middleware in my rest api project:

public async Task InvokeAsync(HttpContext httpContext)              
{                                                                   
    try                                                             
    {                                                               
        await _next(httpContext);                                   
    }                                                                                                                           
    catch (Exception ex)                                            
    {                                                               
        _logger.Error($"{ex}");               
        await HandleExceptionAsync(httpContext);                    
    }                                                               
}    

private Task HandleExceptionAsync(HttpContext context)          
{                                                               
    context.Items.Clear();                                      
    context.Response.StatusCode = StatusCodes.Status200OK;      
    context.Response.ContentType = "application/json";          
                                                                
    return context.Response.WriteAsync("Internal Server Error");
}                                                                    

When some exceptions were catched, i get errors:

System.NullReferenceException: Object reference not set to an instance of an object.
  ?, in Task SaveTempDataFilter.OnStarting(HttpContext httpContext)
  ?, in Task HttpProtocol.FireOnStartingMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onStarting)
System.ObjectDisposedException: The response has been aborted due to an unhandled application exception.
  ?, in void HttpProtocol.ThrowResponseAbortedException()
  ?, in Task HttpProtocol.InitializeResponseAsync(int firstWriteByteCount)
  ?, in Task HttpProtocol.Microsoft.AspNetCore.Http.Features.IHttpResponseBodyFeature.StartAsync(CancellationToken cancellationToken)
  ?, in Task DefaultHttpResponse.StartAsync(CancellationToken cancellationToken)
  ?, in Task HttpResponseWritingExtensions.WriteAsync(HttpResponse response, string text, Encoding encoding, CancellationToken cancellationToken) x 2
  File "/Middleware/ExceptionWrapperMiddleware.cs", line 57, col 13, in Task ExceptionWrapperMiddleware.HandleExceptionAsync(HttpContext context)
  File "/Middleware/ExceptionWrapperMiddleware.cs", line 50, col 9, in async Task ExceptionWrapperMiddleware.InvokeAsync(HttpContext httpContext)
  File "/_/src/Sentry.AspNetCore/SentryMiddleware.cs", line 139, col 9, in async Task SentryMiddleware.InvokeAsync(HttpContext context)

My question is, what is wrong with my code that i get Null Reference Exception and ObjectDisposedException in the same time?

According to the stack trace HttpResponseWritingExtensions.WriteAsync throws an exception when you call context.Response.WriteAsync("Internal Server Error"); method. Instead of returning the task, you just need to await WriteAsync method.

private async Task HandleExceptionAsync(HttpContext context)          
{                                                         
     context.Items.Clear();                                      
     context.Response.StatusCode = StatusCodes.Status200OK;      
     context.Response.ContentType = "application/json";          
                                                            
     return await context.Response.WriteAsync("Internal Server Error");
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM