private async void OnAccept(Stream stream) { try { using (stream) { var onSendingHeadersCallbacks = new List <(Action <object>, object)>(); var owinContext = new OwinContext(); // this is an owin extension owinContext.Set <Action <Action <object>, object> >("server.OnSendingHeaders", (callback, state) => { onSendingHeadersCallbacks.Add((callback, state)); }); owinContext.Set("owin.Version", "1.0"); _logger.WriteVerbose("Server: reading message.."); await PopulateRequestAsync(stream, owinContext.Request, CancellationToken.None).ConfigureAwait(false); // some transports (shuch as Named Pipes) may require the server to read some data before being able to get the // client identity. So we get the client identity after reading the request headers var transportIdentity = _listener.GetTransportIdentity(stream); owinContext.Request.User = transportIdentity; _logger.WriteVerbose("Server: finished reading message"); Func <Task> sendHeadersAsync = async() => { // notify we are sending headers foreach ((var callback, var state) in onSendingHeadersCallbacks) { callback(state); } // send status and headers string statusCode = owinContext.Response.StatusCode.ToString(); _logger.WriteVerbose("Server: Statuscode was " + statusCode); await stream.WriteServerResponseStatusAndHeadersAsync(owinContext.Request.Protocol, statusCode, owinContext.Response.ReasonPhrase, owinContext.Response.Headers.Select(i => new KeyValuePair <string, IEnumerable <string> >(i.Key, i.Value)), _logger.WriteVerbose, CancellationToken.None).ConfigureAwait(false); _logger.WriteVerbose("Server: Wrote status and headers."); await stream.FlushAsync().ConfigureAwait(false); }; var body = new WriteInterceptStream(stream, sendHeadersAsync); owinContext.Response.Body = body; // execute higher level middleware _logger.WriteVerbose("Server: executing middleware.."); try { await _app(owinContext.Environment).ConfigureAwait(false); } catch (Exception e) { await HandleMiddlewareException(e, owinContext, body); } _logger.WriteVerbose("Server: finished executing middleware.."); await body.FlushAsync().ConfigureAwait(false); _logger.WriteVerbose("Server: Finished request. Disposing connection."); } } catch (EndOfStreamException e) { _logger.WriteWarning("Server: Error handling client stream, (Client disconnected early / invalid HTTP request)", e); } catch (Exception e) { _logger.WriteError("Server: Error handling client stream " + e); } }
private async Task HandleMiddlewareException(Exception e, OwinContext owinContext, WriteInterceptStream body) { var logMessage = "Exception trying to execute middleware: " + e; _logger.WriteError(logMessage); owinContext.Response.StatusCode = 500; var payload = Encoding.ASCII.GetBytes("Exception trying to execute middleware. See logs for details."); await body.WriteAsync(payload, 0, payload.Length).ConfigureAwait(false); await body.WriteAsync(_eol, 0, _eol.Length).ConfigureAwait(false); }