本地服务验证server
using System;
using System.Net;class Program
{static void Main(){HttpListener listener = new HttpListener();listener.Prefixes.Add("http://localhost:8080/");listener.Start();Console.WriteLine("服务器已启动,监听中...");while (true){HttpListenerContext context = listener.GetContext();HttpListenerRequest request = context.Request;HttpListenerResponse response = context.Response;// 处理 OPTIONS 请求if (request.HttpMethod == "OPTIONS"){// 设置 CORS 响应头response.AddHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源,生产环境建议指定具体域名response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的 HTTP 方法response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头response.AddHeader("Access-Control-Max-Age", "86400"); // 预检请求的缓存时间(秒)response.StatusCode = (int)HttpStatusCode.NoContent; // OPTIONS 请求通常返回 204 No Content}else{// 处理其他请求response.AddHeader("Access-Control-Allow-Origin", "*");string responseString = "<HTML><BODY>Hello world!</BODY></HTML>";byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);response.ContentLength64 = buffer.Length;System.IO.Stream output = response.OutputStream;output.Write(buffer, 0, buffer.Length);}response.Close();}}
}
关键代码
response.StatusCode = (int)HttpStatusCode.NoContent; // OPTIONS 请求通常返回 204 No Content
安全验证
string authHeader = request.Headers["Authorization"]; // 获取 Authorization 头
string customHeader = request.Headers["X-Custom-Header"]; // 获取自定义头
请求示例
curl -H "Authorization: Basic dXNlcjpwYXNzd29yZA==" -H "X-Custom-Header: TestValue" http://localhost:8080/