From 43a1bc761dfbd0823c13bad812aa30ab463c1d70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=AE=97=E7=A5=9E?= Date: Tue, 23 Nov 2021 08:26:53 +0800 Subject: [PATCH] =?UTF-8?q?Options=20=E8=BF=94=E5=9B=9E204?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Extensions/JT808HttpContextExtensions.cs | 8 ++++++++ src/JT808.Gateway/JT808HttpServer.cs | 7 +++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs b/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs index 46ba45d..a4c85fc 100644 --- a/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs +++ b/src/JT808.Gateway/Extensions/JT808HttpContextExtensions.cs @@ -11,6 +11,14 @@ namespace JT808.Gateway.Extensions { private const string jsonType = "application/json"; + public static void Http204(this HttpListenerContext context) + { + context.Response.StatusCode = (int)HttpStatusCode.NoContent; + context.Response.KeepAlive = false; + context.Response.OutputStream.Close(); + context.Response.Close(); + } + public static async ValueTask Http401(this HttpListenerContext context) { byte[] b = Encoding.UTF8.GetBytes("auth error"); diff --git a/src/JT808.Gateway/JT808HttpServer.cs b/src/JT808.Gateway/JT808HttpServer.cs index b85cb52..f09be38 100644 --- a/src/JT808.Gateway/JT808HttpServer.cs +++ b/src/JT808.Gateway/JT808HttpServer.cs @@ -76,15 +76,18 @@ namespace JT808.Gateway context.Http404(); continue; } + // 增加CORS // https://stackoverflow.com/questions/25437405/cors-access-for-httplistener + context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); if (context.Request.HttpMethod == HttpMethod.Options.Method) { - context.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); + context.Response.AddHeader("Access-Control-Allow-Headers", "*"); context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); context.Response.AddHeader("Access-Control-Max-Age", "1728000"); + context.Http204(); } - context.Response.AppendHeader("Access-Control-Allow-Origin", "*"); + if (authorization.Authorization(context, out var principal)) { await ProcessRequestAsync(context, principal);