Owin Self Host Web Api - 客户端在响应期间关闭连接会引发异常吗?

问题描述 投票:15回答:2

我正在运行一个基于Owin Selfhost的WebApi,我在其中输入了一个API未处理的异常记录器

config.Services.Add(typeof(IExceptionLogger), _apiExceptionLogger);

Api Exception Logger的相关部分:

    public override void Log(ExceptionLoggerContext context)
    {
        if (context == null || context.ExceptionContext == null) return;

        Logger.Error("Unhandled exception from Web API", context.ExceptionContext.Exception);
    }

它定期捕获和记录的情况是客户端请求数据集然后在发送结果(JSON)时关闭连接的人 - 用chrome发出请求,然后在所有结果返回之前点击X按钮: P

我已经粘贴了下面的堆栈跟踪以获得完整性,只想知道两件事:

  • 这是常规/预期的行为吗? AFAIK是......我正在运行一个非常默认的API和管道
  • 有办法处理这个吗?在取消的情况下基本上更优雅地停止请求处理(在整个请求管道中记录的取消令牌确实浮现在脑海中,但在这种情况下它们看起来并不像在所有令牌仅支持合作取消之后)

我没有深入研究套接字级别发生的事件序列,到目前为止,这只是一个日志记录的麻烦。

System.Net.Http.HttpRequestException: Error while copying content to a stream. ---> System.IO.IOException ---> System.Net.HttpListenerException: The I/O operation has been aborted because of either a thread exit or an application request
   at System.Net.HttpResponseStream.EndWrite(IAsyncResult asyncResult)
   at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.EndWrite(IAsyncResult asyncResult)
   --- End of inner exception stack trace ---
   at Microsoft.Owin.Host.HttpListener.RequestProcessing.ExceptionFilterStream.EndWrite(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
   --- End of inner exception stack trace ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<SendResponseContentAsync>d__20.MoveNext()    at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Web.Http.Owin.HttpMessageHandlerAdapter.<SendResponseContentAsync>d__20.MoveNext()
c# .net asp.net-web-api owin
2个回答
4
投票

我在Raspberry Pi上遇到了与Owin主机类似的问题。这可能有助于https://stackoverflow.com/a/30583109/1786034


0
投票

它的代码问题

读取文件异步并检查。如果你正在进行api调用并且它超时它肯定会抛出异常。

using (StreamReader reader = new StreamReader(await selectedFile.OpenStreamForReadAsync()))
            {
                while ((nextLine = await reader.ReadLineAsync()) != null)
                {
                    contents.AppendFormat("{0}. ", lineCounter);
                    contents.Append(nextLine);
                    contents.AppendLine();
                    lineCounter++;
                    if (lineCounter > 3)
                    {
                        contents.AppendLine("Only first 3 lines shown.");
                        break;
                    }
                }
            }
© www.soinside.com 2019 - 2024. All rights reserved.