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 良构校验。
This commit is contained in:
liufumingren 2026-10-17 10:13:09 +08:00
parent 9be56db385
commit 680fff84df
13 changed files with 1137 additions and 0 deletions

9
.gitignore vendored
View File

@ -16,6 +16,15 @@ coverage/
.vite/
*.tsbuildinfo
# ---------- .NET / WPF(desktop/) ----------
bin/
obj/
publish/
artifacts/
.vs/
*.user
*.suo
# ---------- 运行期 / 日志 ----------
# backend 的 logs/、多实例自测时的 logs-test/、脚本产出的 run/
logs/

13
desktop/App.xaml Normal file
View File

@ -0,0 +1,13 @@
<Application x:Class="YuncangTrace.LocalService.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShutdownMode="OnMainWindowClose">
<!-- 没有 StartupUri:窗口在 App.xaml.cs 里创建(要先判断单实例 / 协议参数) -->
<Application.Resources>
<SolidColorBrush x:Key="BrandBrush" Color="#2563EB" />
<SolidColorBrush x:Key="MutedBrush" Color="#6B7280" />
<SolidColorBrush x:Key="LineBrush" Color="#E5E7EB" />
<SolidColorBrush x:Key="OkBrush" Color="#16A34A" />
<SolidColorBrush x:Key="BadBrush" Color="#DC2626" />
</Application.Resources>
</Application>

64
desktop/App.xaml.cs Normal file
View File

@ -0,0 +1,64 @@
using System.Windows;
using YuncangTrace.LocalService.Services;
namespace YuncangTrace.LocalService;
/// <summary>
/// 应用入口
///
/// 两件事:**单实例**(协议被点开时系统会再启动一次本程序,要把参数转给已运行的实例)
/// 和**把窗口拉起来**。
/// </summary>
public partial class App : Application
{
private SingleInstance? _single;
private MainWindow? _window;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
_single = new SingleInstance("YuncangTrace.LocalService", OnSecondInstanceArgs);
// 已经有一个实例在跑:把自己的参数(可能是 yuncang://open?code=xxx)转过去,然后退出
if (!_single.IsFirstInstance)
{
_single.SendArgs(e.Args);
Shutdown();
return;
}
_window = new MainWindow();
MainWindow = _window;
_window.Show();
// 起命名管道监听(接收后续「再次启动」带来的参数)
_single.StartListening();
// 本次就是被协议拉起来的:直接进入「按 code 查信息」
var launchUrl = ProtocolHelper.FirstLaunchUrl(e.Args);
if (launchUrl is not null) _window.HandleLaunchUrl(launchUrl);
}
/// <summary>另一个实例把参数送过来了(工作线程回调,切回 UI 线程)</summary>
private void OnSecondInstanceArgs(string[] args)
{
Dispatcher.Invoke(() =>
{
if (MainWindow is MainWindow window)
{
if (window.WindowState == WindowState.Minimized) window.WindowState = WindowState.Normal;
window.Activate();
var url = ProtocolHelper.FirstLaunchUrl(args);
if (url is not null) window.HandleLaunchUrl(url);
}
});
}
protected override void OnExit(ExitEventArgs e)
{
_single?.Dispose();
base.OnExit(e);
}
}

92
desktop/MainWindow.xaml Normal file
View File

@ -0,0 +1,92 @@
<Window x:Class="YuncangTrace.LocalService.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="云仓视频溯源软件(本机服务)"
Height="620" Width="780"
MinHeight="520" MinWidth="680"
WindowStartupLocation="CenterScreen"
Background="{StaticResource BgBrush}"
FontFamily="Microsoft YaHei UI, Segoe UI"
FontSize="13">
<Grid Margin="18">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!-- ① 标题 + 运行状态 -->
<DockPanel Grid.Row="0" Margin="0,0,0,14">
<TextBlock DockPanel.Dock="Right"
Text="云仓视频溯源系统"
Foreground="{StaticResource MutedBrush}"
VerticalAlignment="Center" />
<StackPanel Orientation="Horizontal">
<Ellipse x:Name="StatusDot" Width="10" Height="10" Margin="0,0,8,0"
VerticalAlignment="Center" Fill="{StaticResource BadBrush}" />
<TextBlock Text="本机服务" FontSize="18" FontWeight="SemiBold" VerticalAlignment="Center" />
<TextBlock x:Name="StatusText" Text="未启动" Margin="10,0,0,2"
Foreground="{StaticResource MutedBrush}" VerticalAlignment="Bottom" />
</StackPanel>
</DockPanel>
<!-- ② 服务地址 -->
<Border Grid.Row="1" Background="White" BorderBrush="{StaticResource LineBrush}"
BorderThickness="1" CornerRadius="8" Padding="12,10" Margin="0,0,0,10">
<DockPanel>
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<Button Content="复制地址" Padding="10,4" Margin="0,0,8,0" Click="CopyAddress_Click" />
<Button Content="在浏览器打开" Padding="10,4" Click="OpenInBrowser_Click" />
</StackPanel>
<TextBlock Text="服务地址" Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" Margin="0,0,10,0" />
<TextBox x:Name="AddressBox" IsReadOnly="True" BorderThickness="0" Background="Transparent"
FontFamily="Consolas, Microsoft YaHei UI" VerticalContentAlignment="Center" />
</DockPanel>
</Border>
<!-- ③ 操作按钮 + 协议状态 -->
<StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,0,0,6">
<Button x:Name="StartStopButton" Content="停止服务" Padding="14,6" Click="StartStop_Click" />
<Button x:Name="ProtocolButton" Content="注册启动协议" Padding="14,6" Margin="10,0,0,0" Click="Protocol_Click" />
<Button Content="复制唤醒地址" Padding="14,6" Margin="10,0,0,0" Click="CopyLaunchUrl_Click" />
<TextBlock x:Name="ProtocolText" Margin="14,0,0,0" VerticalAlignment="Center"
Foreground="{StaticResource MutedBrush}" TextTrimming="CharacterEllipsis" />
</StackPanel>
<!-- ④ 查询测试 -->
<Border Grid.Row="3" Background="White" BorderBrush="{StaticResource LineBrush}"
BorderThickness="1" CornerRadius="8" Padding="12,10" Margin="0,6,0,10">
<StackPanel>
<DockPanel>
<Button DockPanel.Dock="Right" Content="查询" Padding="16,5" Margin="8,0,0,0" Click="Query_Click" />
<TextBlock Text="测试查询" Foreground="{StaticResource MutedBrush}" VerticalAlignment="Center" Margin="0,0,10,0" />
<TextBox x:Name="QueryBox" Padding="6,3" VerticalContentAlignment="Center"
ToolTip="输入运单号后回车" KeyDown="QueryBox_KeyDown" />
</DockPanel>
<TextBox x:Name="ResultBox" Margin="0,10,0,0" Height="130" IsReadOnly="True"
AcceptsReturn="True" AcceptsTab="True" TextWrapping="NoWrap"
VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12" Padding="8"
Background="#F9FAFB" BorderBrush="{StaticResource LineBrush}" />
</StackPanel>
</Border>
<!-- ⑤ 日志 -->
<Grid Grid.Row="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="运行日志" Foreground="{StaticResource MutedBrush}" Margin="2,0,0,4" />
<Border Grid.Row="1" Background="White" BorderBrush="{StaticResource LineBrush}"
BorderThickness="1" CornerRadius="8" Padding="4">
<ListBox x:Name="LogList" BorderThickness="0" Background="Transparent"
FontFamily="Consolas, Microsoft YaHei UI" FontSize="12"
ScrollViewer.HorizontalScrollBarVisibility="Auto" />
</Border>
</Grid>
</Grid>
</Window>

227
desktop/MainWindow.xaml.cs Normal file
View File

@ -0,0 +1,227 @@
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]);
}
}

144
desktop/README.md Normal file
View File

@ -0,0 +1,144 @@
# 云仓视频溯源软件(本机服务 / WPF)
Windows 桌面端,用**前端 `/local` 公共页**和 **Chrome 插件**做对接:
- 在 `127.0.0.1:17311` 起一个本机 HTTP 服务,浏览器里的页面直接查询本机数据;
- 注册 `yuncang://` 启动协议,网页可以「叫醒」本软件(前提是已安装);
- 单实例:被协议再次拉起时,只把 `code` 转给已运行的窗口,不会抢端口。
```
desktop/
├── YuncangTrace.LocalService.csproj # net8.0-windows + UseWPF
├── app.manifest # 高 DPI / 兼容性声明
├── App.xaml / App.xaml.cs # 单实例 + 协议参数处理
├── MainWindow.xaml / .xaml.cs # 状态、地址、协议注册、测试查询、日志
└── Services/
├── LocalHttpServer.cs # HttpListener + CORS + PNA
├── OrderQueryService.cs # ★ 按运单号查数据(接真实数据源的地方)
├── ProtocolHelper.cs # yuncang:// 注册/反注册、解析 code
├── SingleInstance.cs # 互斥体 + 命名管道转发参数
└── JsonUtil.cs # JSON 序列化(中文不转义)
```
## 环境要求
- 编译:**.NET 8 SDK**(`dotnet --list-sdks` 能看到 `8.x`)
- 只运行已发布的 exe:**.NET 8 Desktop Runtime**(不需要 SDK)
> 本仓库当前环境**没有装 .NET**,所以这份代码没在 CI 里编译过;第一次请自己跑一遍
> `dotnet build`,有报错直接贴出来。
## 构建 / 运行 / 发布
```powershell
cd desktop
dotnet build -c Release # 编译
dotnet run # 直接跑(调试)
# 发布给用户装(framework-dependent,体积小、需要装 Desktop Runtime)
dotnet publish -c Release -r win-x64 --self-contained false -o publish
# 或者自带运行时(体积大,但用户什么都不用装)
dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -o publish
```
## 本机接口(前端 `/local` 页用的就是这两个)
服务固定监听 `http://localhost:17311`(端口写在前端页面与插件里)。
代码里**同时注册了 `http://127.0.0.1:17311/`** 前缀 —— `HttpListener` 只接受「注册过的 host」,
不注册的话用 127.0.0.1 访问会直接被回 400(前端改 `VITE_LOCAL_SERVICE` 时就会碰到)。
浏览器直接打开 <http://localhost:17311/> 会看到一个说明页(列了下面两个接口,方便排查)。
| 方法 | 路径 | 说明 |
| --- | --- | --- |
| GET | `/api/health` | 探活:**只要能返回 2xx 就认为软件已启动**。返回 `{ ok, name, version, port, serverTime }` |
| GET | `/api/query/{code}` | 按运单号查信息。**成功时把字段平铺在顶层**(`{ code, orderNo, ... }`),失败返回 `{ ok:false, message }` + 4xx |
示例:
```powershell
curl http://localhost:17311/api/health
curl http://localhost:17311/api/query/321408064481776
```
浏览器跨域(页面在站点域名上,请求的是 localhost)必须回这些响应头,代码里已经处理:
- `Access-Control-Allow-Origin`(回显 Origin)、`Allow-Methods`、`Allow-Headers`、`Max-Age`
- `Access-Control-Allow-Private-Network: true` —— 公网 https 页面访问 localhost 时 Chrome 会发
私有网络预检(PNA),不回这个头预检就失败
> ⚠️ 千万别只回 `200` 不带 CORS 头:浏览器会直接拦掉,前端看起来和「软件没启动」一模一样。
## 启动协议(网页叫醒本软件)
`yuncang://open?code=xxx`。注册写在 **HKCU**(免管理员):
```
HKEY_CURRENT_USER\Software\Classes\yuncang
(默认) = "URL:云仓视频溯源软件"
"URL Protocol" = ""
\shell\open\command
(默认) = "C:\...\YuncangTrace.LocalService.exe" "%1"
```
- 界面上点「**注册启动协议**」即可(指向当前 exe);卸载时点「取消启动协议」或调用 `ProtocolHelper.Unregister()`;
- 手工注册/排查:
```powershell
reg add "HKCU\Software\Classes\yuncang" /ve /d "URL:云仓视频溯源软件" /f
reg add "HKCU\Software\Classes\yuncang" /v "URL Protocol" /d "" /f
reg add "HKCU\Software\Classes\yuncang\shell\open\command" /ve /d '"C:\Path\YuncangTrace.LocalService.exe" "%1"' /f
reg query "HKCU\Software\Classes\yuncang\shell\open\command"
```
- 打包工具里对应:Inno Setup 的 `[Registry]` 段、NSIS 的 `WriteRegStr HKCU ...`、Electron 的
`app.setAsDefaultProtocolClient('yuncang')`;
- 协议名改了要同步前端 `VITE_APP_PROTOCOL`(默认 `yuncang`)。
## 和前端 / 插件怎么配合
1. WMS 页面上点运单号旁的按钮 → 插件打开 `http://<站点>/local?code=<运单号>`;
2. `/local` 页先探活 `http://localhost:17311/api/health`:
- 通 → 直接调 `/api/query/{code}` 展示;
- 不通 → 提示「服务暂不可用 / 本地打印服务未启动,请下载安装后再试」+ 下载按钮;
点「已安装,启动本机软件」会走 `yuncang://open?code=...`,然后每 1s 轮询探活,起来后自动查询。
3. 本软件被协议拉起时,会拿到 `yuncang://open?code=xxx` 参数:已经开着就转给原窗口(单实例),
没开就启动并直接查询这个码。
## ★ 接真实数据
只改一处:`Services/OrderQueryService.cs` 的 `Query(string? code)`。
```csharp
public QueryResult Query(string? code)
{
var value = (code ?? "").Trim();
if (value.Length == 0) return QueryResult.BadRequest("缺少运单号");
// 例:查本地 SQLite / 扫本地打包视频目录 / 调内部接口
var row = _db.FindByCode(value);
if (row is null) return QueryResult.NotFound($"没有找到 {value} 的记录");
return QueryResult.Success(new Dictionary<string, object?>
{
["code"] = row.Code,
["orderNo"] = row.OrderNo,
["printStatus"] = row.PrintStatus,
["videoPath"] = row.VideoPath,
});
}
```
返回对象**平铺**即可,前端页面会把顶层字段渲染成「项目 / 值」两列(字段随便加)。
## 常见问题
| 现象 | 处理 |
| --- | --- |
| 启动报「没有绑定端口的权限」/ `Access is denied (5)` | 管理员执行 `netsh http add urlacl url=http://localhost:17311/ user=%USERNAME%`,或改成以当前用户身份运行 |
| 报端口被占用(错误 32) | 已经开了一个实例(单实例会把参数转过去);检查任务管理器里的残留进程 |
| 网页提示服务不可用,但软件在跑 | 先用浏览器直接打开 `http://localhost:17311/api/health`:打不开→防火墙/端口;打得开→多半是 CORS 头没回 |
| 点网页「启动本机软件」没反应 | 协议没注册(界面看「启动协议」状态);或浏览器拦了自动跳转(必须用户点击) |
| 改了协议名 | 注册表重注册 + 前端 `VITE_APP_PROTOCOL` 同步 + 插件目标地址同步 |

View File

@ -0,0 +1,26 @@
using System.Text.Encodings.Web;
using System.Text.Json;
namespace YuncangTrace.LocalService.Services;
/// <summary>JSON 序列化(中文不转义,方便人看;输出紧凑,省得前端表格里一堆空格)</summary>
public static class JsonUtil
{
private static readonly JsonSerializerOptions Compact = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = false,
};
private static readonly JsonSerializerOptions Pretty = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
WriteIndented = true,
};
/// <summary>接口响应用(紧凑)</summary>
public static string ToJson(object? value) => JsonSerializer.Serialize(value, Compact);
/// <summary>界面展示用(缩进)</summary>
public static string ToPrettyJson(object? value) => JsonSerializer.Serialize(value, Pretty);
}

View File

@ -0,0 +1,255 @@
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();
}
}

View File

@ -0,0 +1,48 @@
namespace YuncangTrace.LocalService.Services;
/// <summary>一次查询的结果(HTTP 层和界面都复用)</summary>
/// <param name="Ok">是否查到</param>
/// <param name="StatusCode">HTTP 状态码(200 / 400 / 404 / 500)</param>
/// <param name="Message">失败原因</param>
/// <param name="Data">成功时的数据(**平铺**一个对象,前端按「项目/值」两列直接渲染)</param>
public sealed record QueryResult(bool Ok, int StatusCode, string Message, object? Data)
{
public static QueryResult Success(object data) => new(true, 200, "ok", data);
public static QueryResult BadRequest(string message) => new(false, 400, message, null);
public static QueryResult NotFound(string message) => new(false, 404, message, null);
public static QueryResult Failed(string message) => new(false, 500, message, null);
}
/// <summary>
/// 按运单号查信息
///
/// ⚠️ **这里是接你们真实数据的地方**:现在返回演示数据(任何 code 都返回同一份)。
/// 真实实现通常是:查本地 SQLite / 扫描本地打包视频目录 / 调内部接口,
/// 然后把结果按字段平铺返回(前端页面按 key-value 展示,字段随你加)。
/// </summary>
public sealed class OrderQueryService
{
public QueryResult Query(string? code)
{
var value = (code ?? string.Empty).Trim();
if (value.Length == 0) return QueryResult.BadRequest("缺少运单号");
// ↓↓↓ 换成真实查询逻辑 ↓↓↓
var data = new Dictionary<string, object?>
{
["code"] = value,
["orderNo"] = "SO-20261017-001",
["channel"] = "CH-1",
["printStatus"] = "已打印",
["scanTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
["videoPath"] = @"D:\video\2026-10-17\demo.mp4",
["source"] = "演示数据(请替换 OrderQueryService.Query)",
};
// ↑↑↑ 换成真实查询逻辑 ↑↑↑
return QueryResult.Success(data);
}
}

View File

@ -0,0 +1,98 @@
using Microsoft.Win32;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 自定义协议(URL Scheme)——「网页叫醒本机应用」的唯一合法方式
///
/// 网页里写 <c>yuncang://open?code=123</c>,浏览器问一句「要打开云仓视频溯源软件吗?」,
/// 系统就会按注册表 <c>HKCU\Software\Classes\yuncang\shell\open\command</c> 找到本 exe 并拉起,
/// 形如:<c>"C:\...\YuncangTrace.LocalService.exe" "yuncang://open?code=123"</c>
///
/// 注意:
/// - 网页**不能**直接执行 exe,也不能拿到返回值(所以还要配合 127.0.0.1 上的 HTTP 服务);
/// - 协议注册在 HKCU,**不需要管理员权限**;
/// - 卸载时应该调用 <see cref="Unregister"/> 把注册表清掉。
/// </summary>
public static class ProtocolHelper
{
/// <summary>协议名(前端用 VITE_APP_PROTOCOL 对齐;改了这里要一起改)</summary>
public const string Scheme = "yuncang";
/// <summary>资源管理器 / 浏览器的提示名</summary>
public const string DisplayName = "云仓视频溯源软件";
/// <summary>拼出唤醒地址:<c>yuncang://open?code=xxx</c></summary>
public static string LaunchUrl(string? code)
{
return string.IsNullOrWhiteSpace(code)
? $"{Scheme}://open"
: $"{Scheme}://open?code={Uri.EscapeDataString(code)}";
}
/// <summary>从命令行参数里找出协议地址(被协议拉起时 Windows 会把它作为第一个参数)</summary>
public static string? FirstLaunchUrl(IEnumerable<string> args)
{
return args.FirstOrDefault(arg =>
arg.StartsWith($"{Scheme}://", StringComparison.OrdinalIgnoreCase));
}
/// <summary>从 <c>yuncang://open?code=xxx</c> 里取出 code(没有就返回 null)</summary>
public static string? ParseCode(string? url)
{
if (string.IsNullOrWhiteSpace(url)) return null;
var index = url.IndexOf('?');
if (index < 0 || index == url.Length - 1) return null;
foreach (var pair in url[(index + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var parts = pair.Split('=', 2);
if (parts.Length == 2 && parts[0].Equals("code", StringComparison.OrdinalIgnoreCase))
{
var value = Uri.UnescapeDataString(parts[1].Replace('+', ' ')).Trim();
return value.Length == 0 ? null : value;
}
}
return null;
}
/// <summary>协议是否已注册</summary>
public static bool IsRegistered()
{
using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\{Scheme}\shell\open\command");
return key?.GetValue(null) is string value && value.Length > 0;
}
/// <summary>当前注册的命令行(界面上展示,方便排查指向了哪个 exe)</summary>
public static string? RegisteredCommand()
{
using var key = Registry.CurrentUser.OpenSubKey($@"Software\Classes\{Scheme}\shell\open\command");
return key?.GetValue(null) as string;
}
/// <summary>注册协议(指向当前 exe;HKCU,免管理员)</summary>
public static void Register()
{
var exePath = Environment.ProcessPath
?? throw new InvalidOperationException("拿不到当前程序的路径,无法注册启动协议");
using (var scheme = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{Scheme}"))
{
scheme.SetValue(null, $"URL:{DisplayName}");
scheme.SetValue("URL Protocol", string.Empty);
}
using (var command = Registry.CurrentUser.CreateSubKey($@"Software\Classes\{Scheme}\shell\open\command"))
{
command.SetValue(null, $"\"{exePath}\" \"%1\"");
}
}
/// <summary>取消注册(卸载时调用)</summary>
public static void Unregister()
{
Registry.CurrentUser.DeleteSubKeyTree($@"Software\Classes\{Scheme}", throwOnMissingSubKey: false);
}
}

View File

@ -0,0 +1,117 @@
using System.IO;
using System.IO.Pipes;
using System.Text;
namespace YuncangTrace.LocalService.Services;
/// <summary>
/// 单实例 + 参数转发(命名管道)
///
/// 场景:窗口已经开着,用户又点了一次 WMS 页面上的「查看打包视频」→ 系统按协议再启动一次本程序。
/// 这时第二个实例**不应该**去抢 17311 端口,而是把 `yuncang://open?code=xxx` 通过管道送给第一个实例,
/// 由它把窗口激活并查询那个运单号。
/// </summary>
public sealed class SingleInstance : IDisposable
{
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly Action<string[]> _onArgs;
private readonly CancellationTokenSource _cts = new();
private readonly bool _ownsMutex;
/// <summary>本次是否是第一个实例(不是的话调用 <see cref="SendArgs"/> 后就可以退出了)</summary>
public bool IsFirstInstance { get; }
public SingleInstance(string name, Action<string[]> onArgs)
{
_onArgs = onArgs;
_pipeName = $"{name}.pipe";
// 全局命名互斥体:跨会话也能认出来(同一个用户下就够了,用 Local\ 前缀)
_mutex = new Mutex(initiallyOwned: true, $@"Local\{name}.mutex", out var createdNew);
_ownsMutex = createdNew;
IsFirstInstance = createdNew;
}
/// <summary>第一个实例调用:开一个后台线程等第二个实例送参数过来</summary>
public void StartListening()
{
var thread = new Thread(ListenLoop)
{
IsBackground = true,
Name = "single-instance-pipe",
};
thread.Start();
}
/// <summary>第二个实例调用:把命令行参数送给已运行的实例(连不上就算了,不影响退出)</summary>
public void SendArgs(string[] args)
{
if (args.Length == 0) return;
try
{
using var client = new NamedPipeClientStream(".", _pipeName, PipeDirection.Out);
client.Connect(1500);
using var writer = new StreamWriter(client, new UTF8Encoding(false)) { AutoFlush = true };
foreach (var arg in args) writer.WriteLine(arg);
}
catch (Exception)
{
// 拿不到第一个实例(可能正在退出):静默忽略,用户重新点一次即可
}
}
private void ListenLoop()
{
while (!_cts.IsCancellationRequested)
{
try
{
using var server = new NamedPipeServerStream(
_pipeName, PipeDirection.In, NamedPipeServerStream.MaxAllowedServerInstances,
PipeTransmissionMode.Byte, PipeOptions.None);
server.WaitForConnection();
var args = new List<string>();
using (var reader = new StreamReader(server, new UTF8Encoding(false)))
{
string? line;
while ((line = reader.ReadLine()) is not null)
{
if (line.Length > 0) args.Add(line);
}
}
if (args.Count > 0) _onArgs(args.ToArray());
}
catch (Exception)
{
if (_cts.IsCancellationRequested) return;
Thread.Sleep(200);
}
}
}
public void Dispose()
{
_cts.Cancel();
if (_ownsMutex)
{
try
{
_mutex.ReleaseMutex();
}
catch (ApplicationException)
{
// 不持有互斥体(理论上不会发生)
}
}
_mutex.Dispose();
_cts.Dispose();
}
}

View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<!-- WPF 只能跑在 Windows 上;net8.0-windows 是当前 LTS -->
<TargetFramework>net8.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<!-- 产物名/程序集名(安装包里 exe 就叫这个) -->
<AssemblyName>YuncangTrace.LocalService</AssemblyName>
<RootNamespace>YuncangTrace.LocalService</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
<Version>1.0.0</Version>
<Product>云仓视频溯源软件</Product>
<Company>云仓</Company>
<AssemblyTitle>云仓视频溯源软件(本机服务)</AssemblyTitle>
<NeutralLanguage>zh-CN</NeutralLanguage>
</PropertyGroup>
</Project>

20
desktop/app.manifest Normal file
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="YuncangTrace.LocalService.app" />
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<!-- 高 DPI 下别让 WPF 被系统拉伸(否则字发虚) -->
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 / 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
</assembly>