给前端 `/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 良构校验。
228 lines
6.7 KiB
C#
228 lines
6.7 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.Diagnostics;
|
||
using System.Net;
|
||
using System.Windows;
|
||
using System.Windows.Input;
|
||
using System.Windows.Media;
|
||
using YuncangTrace.LocalService.Services;
|
||
|
||
namespace YuncangTrace.LocalService;
|
||
|
||
/// <summary>
|
||
/// 主窗口:起/停本机 HTTP 服务、注册启动协议、手工测一条查询、看日志
|
||
///
|
||
/// 服务地址固定 <c>http://localhost:17311</c>(前端公共页 /local 与 Chrome 插件都按这个地址写死)。
|
||
/// </summary>
|
||
public partial class MainWindow : Window
|
||
{
|
||
private readonly ObservableCollection<string> _logs = new();
|
||
private readonly OrderQueryService _queryService = new();
|
||
private readonly LocalHttpServer _server;
|
||
|
||
public MainWindow()
|
||
{
|
||
InitializeComponent();
|
||
|
||
_server = new LocalHttpServer(_queryService);
|
||
_server.Log += AppendLog;
|
||
|
||
LogList.ItemsSource = _logs;
|
||
AddressBox.Text = _server.BaseUrl;
|
||
|
||
Loaded += (_, _) =>
|
||
{
|
||
StartServer();
|
||
UpdateProtocolState();
|
||
};
|
||
Closed += (_, _) => _server.Dispose();
|
||
}
|
||
|
||
/// <summary>
|
||
/// 被协议拉起 / 另一个实例把参数转过来时调用:<c>yuncang://open?code=xxx</c>
|
||
/// </summary>
|
||
public void HandleLaunchUrl(string url)
|
||
{
|
||
AppendLog($"收到启动协议:{url}");
|
||
|
||
var code = ProtocolHelper.ParseCode(url);
|
||
if (code is null)
|
||
{
|
||
AppendLog("协议里没带 code,忽略");
|
||
return;
|
||
}
|
||
|
||
QueryBox.Text = code;
|
||
RunQuery();
|
||
}
|
||
|
||
// ---------------- 服务启停 ----------------
|
||
|
||
private void StartServer()
|
||
{
|
||
try
|
||
{
|
||
_server.Start();
|
||
}
|
||
catch (HttpListenerException ex)
|
||
{
|
||
var hint = ex.ErrorCode switch
|
||
{
|
||
5 => "没有绑定端口的权限。用管理员执行一次:netsh http add urlacl url=http://localhost:17311/ user=%USERNAME%",
|
||
32 => "端口 17311 已被占用(可能已经开了一个本程序的实例)。",
|
||
_ => "启动失败:" + ex.Message,
|
||
};
|
||
AppendLog(hint);
|
||
MessageBox.Show(this, hint, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppendLog($"启动失败:{ex.Message}");
|
||
MessageBox.Show(this, ex.Message, "本机服务启动失败", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
|
||
UpdateServerState();
|
||
}
|
||
|
||
private void StartStop_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
if (_server.IsRunning)
|
||
{
|
||
_server.Stop();
|
||
}
|
||
else
|
||
{
|
||
StartServer();
|
||
}
|
||
|
||
UpdateServerState();
|
||
}
|
||
|
||
private void UpdateServerState()
|
||
{
|
||
var running = _server.IsRunning;
|
||
|
||
StatusText.Text = running ? $"运行中 · {_server.BaseUrl}" : "未启动";
|
||
StatusDot.Fill = (Brush)FindResource(running ? "OkBrush" : "BadBrush");
|
||
StartStopButton.Content = running ? "停止服务" : "启动服务";
|
||
}
|
||
|
||
// ---------------- 启动协议 ----------------
|
||
|
||
private void Protocol_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
if (ProtocolHelper.IsRegistered())
|
||
{
|
||
var answer = MessageBox.Show(this,
|
||
"已注册启动协议。要取消注册吗?(取消后网页就无法叫醒本软件)",
|
||
"启动协议", MessageBoxButton.YesNo, MessageBoxImage.Question);
|
||
if (answer != MessageBoxResult.Yes) return;
|
||
|
||
ProtocolHelper.Unregister();
|
||
AppendLog("已取消注册启动协议");
|
||
}
|
||
else
|
||
{
|
||
ProtocolHelper.Register();
|
||
AppendLog($"已注册启动协议:{ProtocolHelper.Scheme}:// → {ProtocolHelper.RegisteredCommand()}");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppendLog($"操作启动协议失败:{ex.Message}");
|
||
MessageBox.Show(this, ex.Message, "启动协议", MessageBoxButton.OK, MessageBoxImage.Warning);
|
||
}
|
||
|
||
UpdateProtocolState();
|
||
}
|
||
|
||
private void UpdateProtocolState()
|
||
{
|
||
var registered = ProtocolHelper.IsRegistered();
|
||
|
||
ProtocolButton.Content = registered ? "取消启动协议" : "注册启动协议";
|
||
ProtocolText.Text = registered
|
||
? $"已注册 {ProtocolHelper.Scheme}://(网页可叫醒本软件)"
|
||
: $"未注册 {ProtocolHelper.Scheme}://(网页无法叫醒本软件)";
|
||
}
|
||
|
||
// ---------------- 查询 ----------------
|
||
|
||
private void Query_Click(object sender, RoutedEventArgs e) => RunQuery();
|
||
|
||
private void QueryBox_KeyDown(object sender, KeyEventArgs e)
|
||
{
|
||
if (e.Key == Key.Enter) RunQuery();
|
||
}
|
||
|
||
private void RunQuery()
|
||
{
|
||
var code = QueryBox.Text.Trim();
|
||
AppendLog($"查询:{code}");
|
||
|
||
var result = _queryService.Query(code);
|
||
ResultBox.Text = result.Ok
|
||
? JsonUtil.ToPrettyJson(result.Data)
|
||
: $"{(int)result.StatusCode} {result.Message}";
|
||
|
||
ResultBox.ScrollToHome();
|
||
}
|
||
|
||
// ---------------- 小工具 ----------------
|
||
|
||
private void CopyAddress_Click(object sender, RoutedEventArgs e) => CopyText(_server.BaseUrl);
|
||
|
||
private void CopyLaunchUrl_Click(object sender, RoutedEventArgs e)
|
||
=> CopyText(ProtocolHelper.LaunchUrl(QueryBox.Text.Trim()));
|
||
|
||
private void OpenInBrowser_Click(object sender, RoutedEventArgs e)
|
||
{
|
||
try
|
||
{
|
||
Process.Start(new ProcessStartInfo($"{_server.BaseUrl}/api/health") { UseShellExecute = true });
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppendLog($"打开浏览器失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
private void CopyText(string text)
|
||
{
|
||
try
|
||
{
|
||
Clipboard.SetText(text);
|
||
AppendLog($"已复制:{text}");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
AppendLog($"复制失败:{ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>日志(服务线程也会调,切回 UI 线程再改集合)</summary>
|
||
private void AppendLog(string message)
|
||
{
|
||
var line = $"[{DateTime.Now:HH:mm:ss}] {message}";
|
||
|
||
if (!Dispatcher.CheckAccess())
|
||
{
|
||
Dispatcher.BeginInvoke(new Action(() => Append(line)));
|
||
return;
|
||
}
|
||
|
||
Append(line);
|
||
}
|
||
|
||
private void Append(string line)
|
||
{
|
||
_logs.Add(line);
|
||
|
||
// 只留最近 300 行,免得越跑越占内存
|
||
while (_logs.Count > 300) _logs.RemoveAt(0);
|
||
|
||
if (_logs.Count > 0) LogList.ScrollIntoView(_logs[^1]);
|
||
}
|
||
}
|