public override Task Invoke(IOwinContext context) { var cookies = new Dictionary <string, string>(); foreach (var pair in context.Request.Cookies) { cookies.Add(pair.Key, pair.Value); } Context.Current = new Context { Cookies = cookies, }; var response = context.Response; try { return(_Instance.RequestWrapper(() => { var uri = context.Request.Uri; string path = uri.PathAndQuery; if (path.Length == 0) { throw new MiddlewareException("Path is empty."); } if (path == "/favicon.ico") { response.StatusCode = 404; return response.WriteAsync("Not found."); } string output = _Instance.GetCachedResponse(context); if (output == null) { TimeSpan invokeDuration; TimeSpan renderDuration; output = ProcessRequest(context, out invokeDuration, out renderDuration); _Instance.OnResponse(context, output, invokeDuration, renderDuration); } var task = context.Response.WriteAsync(output); return task; })); } catch (Exception exception) { var targetInvocationException = exception as TargetInvocationException; if (targetInvocationException != null) { exception = targetInvocationException.InnerException; } Logger.Error("Request error: {0} ({1})", exception.Message, exception.GetType()); response.StatusCode = 500; response.ContentType = "text/plain"; string message; string remoteAddress = context.Request.RemoteIpAddress; bool isLocal = remoteAddress == "127.0.0.1" || remoteAddress == "::1"; if (exception.GetType() == typeof(MiddlewareException) || isLocal) { message = string.Format("{0}\n{1}", exception.Message, exception.StackTrace); } else { message = "An error occurred."; } return(response.WriteAsync(message)); } finally { Context.Current = null; } }