packServer/desktop/Services/LocalHttpServer.cs
liufumingren 680fff84df desktop:新增 WPF 本机软件(本机 HTTP 服务 + yuncang:// 启动协议)
给前端 `/local` 公共页与 Chrome 插件对接的本机软件(net8.0-windows + UseWPF):

- Services/LocalHttpServer.cs:HttpListener 监听 localhost:17311(同时注册 127.0.0.1 前缀)
  - GET /api/health      探活(2xx 即认为已启动)
  - GET /api/query/{code} 按运单号查信息,成功时字段平铺返回
  - CORS 全量响应头 + Access-Control-Allow-Private-Network(公网 https 页面访问 localhost 的
    PNA 预检),预检 OPTIONS 直接 204
  - 根路径给一个说明页,方便浏览器里手工排查
- Services/OrderQueryService.cs:★ 接真实数据源的位置(现为演示数据)
- Services/ProtocolHelper.cs:HKCU\Software\Classes\yuncang 注册/反注册、解析
  yuncang://open?code=xxx(免管理员)
- Services/SingleInstance.cs:互斥体 + 命名管道,被协议再次拉起时把参数转给已运行窗口,
  不会去抢 17311 端口
- MainWindow:运行状态、服务地址(复制/浏览器打开)、注册启动协议、测试查询、运行日志
- App.xaml.cs:单实例判断 + 协议参数处理;启动即自动起服务

README 里写了编译/发布命令、接口契约、协议注册(含 reg 命令与打包工具做法)、
接真实数据的示例,以及端口权限(netsh http add urlalloc)/端口占用等常见问题。

⚠️ 本机没装 .NET SDK,无法在这里编译验证;XAML/manifest/csproj 已做 XML 良构校验。
2026-10-17 10:13:09 +08:00

256 lines
9.7 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Net;
using System.Text;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 本机 HTTP 服务(只监听 127.0.0.1)
///
/// 给浏览器里的页面调用(我们的 `/local` 公共页、以及任何想取数据的前端):
/// - <c>GET /api/health</c> 探活:返回 2xx 即认为「软件已启动」
/// - <c>GET /api/query/{code}</c> 按运单号查信息,成功时**平铺**返回字段
///
/// ⚠️ 两个坑(都在这里处理好了):
/// 1. **CORS**:页面同源是站点域名,请求本机属于跨域,必须回
/// `Access-Control-Allow-Origin` 等头,否则浏览器直接拦掉(表现像「服务没启动」);
/// 2. **Private Network Access**:公网 https 页面访问 localhost 时,Chrome 会先发
/// 带 `Access-Control-Request-Private-Network: true` 的预检,必须回
/// `Access-Control-Allow-Private-Network: true`,否则预检失败。
///
/// 用 <see cref="HttpListener"/>(HTTP.sys):绑定 `http://localhost:端口/` 一般不需要管理员权限;
/// 若报「拒绝访问(5)」,用管理员执行一次:
/// <c>netsh http add urlacl url=http://localhost:17311/ user=%USERNAME%</c>
/// </summary>
public sealed class LocalHttpServer : IDisposable
{
/// <summary>监听端口(前端/插件里写死的 17311)</summary>
public const int Port = 17311;
private readonly HttpListener _listener = new();
private readonly OrderQueryService _queryService;
private CancellationTokenSource? _cts;
private Task? _loop;
/// <summary>日志回调(服务线程 → UI 线程的桥,UI 那边自己 Dispatcher.Invoke)</summary>
public event Action<string>? Log;
public LocalHttpServer(OrderQueryService queryService)
{
_queryService = queryService;
}
/// <summary>浏览器里可直接打开的地址</summary>
public string BaseUrl => $"http://localhost:{Port}";
public bool IsRunning => _listener.IsListening;
/// <summary>启动监听;失败抛 <see cref="HttpListenerException"/>(端口被占 / 没权限)</summary>
public void Start()
{
if (IsRunning) return;
_listener.Prefixes.Clear();
// 两个都监听:前端页面默认用 localhost,但改 VITE_LOCAL_SERVICE 用 127.0.0.1 时也得能连
// (HttpListener 只接受 "注册过的 host",否则直接 400)
_listener.Prefixes.Add($"{BaseUrl}/");
_listener.Prefixes.Add($"http://127.0.0.1:{Port}/");
_listener.Start();
_cts = new CancellationTokenSource();
_loop = Task.Run(() => AcceptLoopAsync(_cts.Token));
Log?.Invoke($"服务已启动:{BaseUrl}");
}
public void Stop()
{
if (!IsRunning) return;
try
{
_cts?.Cancel();
_listener.Stop();
_listener.Close();
}
catch (Exception ex)
{
Log?.Invoke($"停止服务时出错:{ex.Message}");
}
finally
{
Log?.Invoke("服务已停止");
}
}
private async Task AcceptLoopAsync(CancellationToken token)
{
while (!token.IsCancellationRequested && _listener.IsListening)
{
HttpListenerContext context;
try
{
context = await _listener.GetContextAsync().ConfigureAwait(false);
}
catch (Exception)
{
// Stop()/Close() 会让 GetContextAsync 抛异常,属于正常退出路径
break;
}
_ = Task.Run(() => HandleAsync(context), CancellationToken.None);
}
}
private async Task HandleAsync(HttpListenerContext context)
{
var request = context.Request;
var response = context.Response;
try
{
WriteCorsHeaders(request, response);
// 预检请求(含 PNA 预检)直接放行
if (request.HttpMethod.Equals("OPTIONS", StringComparison.OrdinalIgnoreCase))
{
response.StatusCode = 204;
response.Close();
return;
}
var path = request.Url?.AbsolutePath ?? "/";
Log?.Invoke($"{request.HttpMethod} {path} ← {request.RemoteEndPoint?.Address}");
if (!request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
{
await WriteJsonAsync(response, 405, new { ok = false, message = "只支持 GET" }).ConfigureAwait(false);
return;
}
if (path.Equals("/api/health", StringComparison.OrdinalIgnoreCase)
|| path.Equals("/api/health/", StringComparison.OrdinalIgnoreCase))
{
await WriteJsonAsync(response, 200, new
{
ok = true,
name = "云仓视频溯源打印服务",
version = typeof(LocalHttpServer).Assembly.GetName().Version?.ToString() ?? "1.0.0",
port = Port,
serverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
}).ConfigureAwait(false);
return;
}
const string queryPrefix = "/api/query/";
if (path.StartsWith(queryPrefix, StringComparison.OrdinalIgnoreCase))
{
var code = Uri.UnescapeDataString(path[queryPrefix.Length..]).Trim();
var result = _queryService.Query(code);
if (result.Ok)
{
await WriteJsonAsync(response, 200, result.Data).ConfigureAwait(false);
}
else
{
await WriteJsonAsync(response, result.StatusCode, new { ok = false, message = result.Message }).ConfigureAwait(false);
}
return;
}
// 浏览器直接打开本机服务时给一个说明页(方便排查、也是手工测试入口)
if (path == "/" || path.Equals("/index.html", StringComparison.OrdinalIgnoreCase))
{
var html = """
<!doctype html><meta charset="utf-8">
<title>云仓视频溯源软件(本机服务)</title>
<style>body{font:14px/1.7 "Microsoft YaHei UI",sans-serif;margin:40px;color:#1f2430}
code{background:#f3f4f6;padding:1px 6px;border-radius:5px}a{color:#2563eb}</style>
<h2>云仓视频溯源软件(本机服务)</h2>
<p>服务运行中,只监听本机(127.0.0.1:17311)。</p>
<ul>
<li><a href="/api/health">/api/health</a> 探活</li>
<li><code>/api/query/{运单号}</code> 按运单号查信息</li>
</ul>
""";
await WriteHtmlAsync(response, 200, html).ConfigureAwait(false);
return;
}
await WriteJsonAsync(response, 404, new { ok = false, message = "接口不存在" }).ConfigureAwait(false);
}
catch (Exception ex)
{
Log?.Invoke($"处理请求出错:{ex.Message}");
try
{
await WriteJsonAsync(response, 500, new { ok = false, message = "本机服务内部错误" }).ConfigureAwait(false);
}
catch
{
// 响应已经发出去 / 连接断了,忽略
}
}
finally
{
try
{
response.Close();
}
catch
{
// 忽略
}
}
}
/// <summary>CORS + 私有网络访问(PNA)头</summary>
private static void WriteCorsHeaders(HttpListenerRequest request, HttpListenerResponse response)
{
// 回显 Origin(比写死 * 更稳:以后要带 cookie/凭据也能用)
var origin = request.Headers["Origin"];
response.Headers["Access-Control-Allow-Origin"] = string.IsNullOrEmpty(origin) ? "*" : origin;
response.Headers["Vary"] = "Origin";
response.Headers["Access-Control-Allow-Methods"] = "GET, OPTIONS";
response.Headers["Access-Control-Allow-Headers"] = "Content-Type, Accept";
response.Headers["Access-Control-Max-Age"] = "600";
// 公网页面访问 localhost 时,Chrome 会带 Access-Control-Request-Private-Network: true
if (string.Equals(request.Headers["Access-Control-Request-Private-Network"], "true", StringComparison.OrdinalIgnoreCase))
{
response.Headers["Access-Control-Allow-Private-Network"] = "true";
}
}
private static async Task WriteJsonAsync(HttpListenerResponse response, int statusCode, object? payload)
{
var body = JsonUtil.ToJson(payload);
await WriteTextAsync(response, statusCode, "application/json; charset=utf-8", body).ConfigureAwait(false);
}
private static async Task WriteHtmlAsync(HttpListenerResponse response, int statusCode, string html)
{
await WriteTextAsync(response, statusCode, "text/html; charset=utf-8", html).ConfigureAwait(false);
}
private static async Task WriteTextAsync(HttpListenerResponse response, int statusCode, string contentType, string body)
{
var bytes = Encoding.UTF8.GetBytes(body);
response.StatusCode = statusCode;
response.ContentType = contentType;
response.ContentEncoding = Encoding.UTF8;
response.Headers["Cache-Control"] = "no-store";
response.ContentLength64 = bytes.Length;
await response.OutputStream.WriteAsync(bytes).ConfigureAwait(false);
}
public void Dispose()
{
Stop();
_cts?.Dispose();
_listener.Close();
}
}