diff --git a/Tranga/Server.cs b/Tranga/Server.cs index e2f19f0..73ab7b6 100644 --- a/Tranga/Server.cs +++ b/Tranga/Server.cs @@ -712,6 +712,10 @@ public class Server : GlobalBase private void SendResponse(HttpStatusCode statusCode, HttpListenerResponse response, object? content = null) { + if (response.OutputStream.CanWrite == false) + { + Log($"No response sent to request: Stream closed before response could be sent."); + } //Log($"Response: {statusCode} {content}"); response.StatusCode = (int)statusCode; response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); @@ -719,43 +723,43 @@ public class Server : GlobalBase response.AddHeader("Access-Control-Max-Age", "1728000"); response.AppendHeader("Access-Control-Allow-Origin", "*"); - if (content is not Stream) + try { - response.ContentType = "application/json"; - try + if (content is not Stream) { + response.ContentType = "application/json"; response.OutputStream.Write(content is not null ? Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content)) : Array.Empty()); - response.OutputStream.Close(); } - catch (HttpListenerException e) + else if (content is FileStream stream) { - Log(e.ToString()); + string contentType = stream.Name.Split('.')[^1]; + switch (contentType.ToLower()) + { + case "gif": + response.ContentType = "image/gif"; + break; + case "png": + response.ContentType = "image/png"; + break; + case "jpg": + case "jpeg": + response.ContentType = "image/jpeg"; + break; + case "log": + response.ContentType = "text/plain"; + break; + } + + stream.CopyTo(response.OutputStream); + stream.Close(); } - } - else if(content is FileStream stream) - { - string contentType = stream.Name.Split('.')[^1]; - switch (contentType.ToLower()) - { - case "gif": - response.ContentType = "image/gif"; - break; - case "png": - response.ContentType = "image/png"; - break; - case "jpg": - case "jpeg": - response.ContentType = "image/jpeg"; - break; - case "log": - response.ContentType = "text/plain"; - break; - } - stream.CopyTo(response.OutputStream); response.OutputStream.Close(); - stream.Close(); + } + catch (HttpListenerException e) + { + Log(e.ToString()); } } } \ No newline at end of file