From 9b8b80cd2462ff0979c9405f1811c461a57f899f Mon Sep 17 00:00:00 2001 From: Glax Date: Sat, 7 Sep 2024 20:36:00 +0200 Subject: [PATCH] Fix response closed on OPTIONS request --- Tranga/Server.cs | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/Tranga/Server.cs b/Tranga/Server.cs index 4e387f15..dbf80a51 100644 --- a/Tranga/Server.cs +++ b/Tranga/Server.cs @@ -63,10 +63,11 @@ private void HandleRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; - if(request.HttpMethod == "OPTIONS") - SendResponse(HttpStatusCode.OK, context.Response); - if(request.Url!.LocalPath.Contains("favicon")) + if (request.Url!.LocalPath.Contains("favicon")) + { SendResponse(HttpStatusCode.NoContent, response); + return; + } switch (request.HttpMethod) { @@ -79,7 +80,10 @@ private void HandleRequest(HttpListenerContext context) case "DELETE": HandleDelete(request, response); break; - default: + case "OPTIONS": + SendResponse(HttpStatusCode.OK, context.Response); + break; + default: SendResponse(HttpStatusCode.BadRequest, response); break; } @@ -707,14 +711,15 @@ private void HandleDelete(HttpListenerRequest request, HttpListenerResponse resp private void SendResponse(HttpStatusCode statusCode, HttpListenerResponse response, object? content = null) { //Log($"Response: {statusCode} {content}"); + response.StatusCode = (int)statusCode; response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); response.AddHeader("Access-Control-Allow-Methods", "GET, POST, DELETE"); response.AddHeader("Access-Control-Max-Age", "1728000"); response.AppendHeader("Access-Control-Allow-Origin", "*"); - try { + if (content is not Stream) { response.ContentType = "application/json"; @@ -750,7 +755,7 @@ private void SendResponse(HttpStatusCode statusCode, HttpListenerResponse respon stream.Close(); } } - catch (HttpListenerException e) + catch (Exception e) { Log(e.ToString()); }