2
0

Fix crash when outputstream closes before response could be sent.

#227
This commit is contained in:
Glax 2024-08-26 10:38:45 +02:00
parent 59547efab2
commit db73af3bdd

View File

@ -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,22 +723,16 @@ public class Server : GlobalBase
response.AddHeader("Access-Control-Max-Age", "1728000");
response.AppendHeader("Access-Control-Allow-Origin", "*");
try
{
if (content is not Stream)
{
response.ContentType = "application/json";
try
{
response.OutputStream.Write(content is not null
? Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(content))
: Array.Empty<byte>());
response.OutputStream.Close();
}
catch (HttpListenerException e)
{
Log(e.ToString());
}
}
else if(content is FileStream stream)
else if (content is FileStream stream)
{
string contentType = stream.Name.Split('.')[^1];
switch (contentType.ToLower())
@ -753,9 +751,15 @@ public class Server : GlobalBase
response.ContentType = "text/plain";
break;
}
stream.CopyTo(response.OutputStream);
response.OutputStream.Close();
stream.Close();
}
response.OutputStream.Close();
}
catch (HttpListenerException e)
{
Log(e.ToString());
}
}
}