[英]System.ObjectDisposedException on a socket and when to close streams
[英]System.ObjectDisposedException when writing into HttpContext
我在我的 rest api 项目中制作了自定义异常中间件:
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");
}
当捕获到一些异常时,我收到错误:
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)
我的问题是,我的代码同时得到 Null Reference Exception 和 ObjectDisposedException 有什么问题?
根据堆栈跟踪,当您调用context.Response.WriteAsync("Internal Server Error");
时, HttpResponseWritingExtensions.WriteAsync
会引发异常context.Response.WriteAsync("Internal Server Error");
方法。 您只需要等待WriteAsync
方法,而不是返回任务。
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.