packServer/desktop/Services/LocalHttpServer.cs
liufumingren 51abccbaaf desktop:加登录页、托盘图标、防多开(单实例 + 参数转发)
- LoginWindow:服务器地址 / 账号 / 密码 / 记住账号 → POST /api/web/auth/login 拿 user JWT;
  本地已有令牌时先用 GET /api/web/me 验证,有效就跳过登录(窗口一闪而过),无效清掉令牌留下重登。
- TrayIconService(WinForms NotifyIcon,csproj 开 UseWindowsForms):
  关窗口 = 隐藏到托盘(本机服务继续跑),双击托盘恢复,右键菜单「打开主界面 / 服务地址 / 版本 / 退出」;
  第一次缩到托盘冒一次气泡提示。退出只走托盘「退出」(App 改 ShutdownMode=OnExplicitShutdown)。
- 防多开:SingleInstance(Local\ 命名互斥体 + 命名管道)。第二个实例不抢 17311 端口,
  把 yuncang://open?code=… 转给已运行实例(在托盘里也会被弹出来并按 code 查询)后自己退出;
  还在登录界面时先把 URL 存起来,登录完成后再查。
- 生命周期调整:本机 HTTP 服务与托盘在 App 里创建(登录前就可用),主窗口只管展示与操作;
  日志改成全局 AppLog(窗口没开时的日志也会在窗口打开后补上)。
- 新增 AppSettings / SessionStore:%LOCALAPPDATA%\YuncangTrace\settings.json、session.json
  (服务器地址默认 http://127.0.0.1:7300;换服务器不会复用旧令牌)。
- 新增 ApiClient(登录 / 校验令牌)、MainWindow「退出登录」(清令牌回登录页)。
- 程序/托盘图标:Assets/app.ico + tools/make-icon.ps1(品牌蓝 + 白色播放三角)。
- csproj 关闭 ImplicitUsings:WPF 与 WinForms 同时开启时隐式命名空间会让
  MessageBox / Application / Clipboard 等产生歧义。

⚠️ 本机没有 .NET SDK,无法编译验证;已做 XAML/XML 良构与括号平衡检查。
2026-10-17 10:23:50 +08:00

259 lines
9.8 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;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
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();
}
}