diff --git a/desktop/App.xaml b/desktop/App.xaml index 319fb98..83d5791 100644 --- a/desktop/App.xaml +++ b/desktop/App.xaml @@ -10,5 +10,7 @@ + + diff --git a/desktop/App.xaml.cs b/desktop/App.xaml.cs index 62529cd..2af583b 100644 --- a/desktop/App.xaml.cs +++ b/desktop/App.xaml.cs @@ -45,6 +45,7 @@ public partial class App : Application } _settings = AppSettings.Load(); + ApplyServerOverride(e.Args); _pendingLaunchUrl = ProtocolHelper.FirstLaunchUrl(e.Args); // ② 本机服务先起来(和登录状态无关) @@ -53,6 +54,7 @@ public partial class App : Application // 网页靠 /api/health 里的 loggedIn 判断要不要唤起登录,靠 /api/activate-login 把登录窗叫到前台 _server.IsLoggedInProvider = () => _session is not null; _server.UserNameProvider = () => _session?.DisplayName; + _server.ServerBaseUrlProvider = () => _settings.ServerBaseUrl; _server.LoginRequested += OnLoginRequested; StartLocalServer(); @@ -64,6 +66,7 @@ public partial class App : Application UpdateTrayStatus(); AppLog.Write($"本机服务:{_server.BaseUrl}({(_server.IsRunning ? "运行中" : "未启动")})"); + AppLog.Write($"环境:{BuildInfo.EnvironmentLabel},后端:{_settings.ServerBaseUrl}"); // ④ 登录 → 主窗口 if (!ShowLogin()) @@ -78,6 +81,38 @@ public partial class App : Application // ---------------- 登录 ---------------- + /// + /// 后端地址的运行时覆盖(优先级:--server=xxx 参数 > YUNCANG_SERVER 环境变量 > 构建默认值) + /// + /// 打包/联调时用:YuncangTrace.LocalService.exe --server=http://192.168.1.10:7300 + /// + private void ApplyServerOverride(string[] args) + { + string? url = null; + + for (var i = 0; i < args.Length; i++) + { + var arg = args[i]; + const string prefix = "--server="; + + if (arg.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + url = arg[prefix.Length..]; + } + else if ((arg == "--server" || arg == "-s") && i + 1 < args.Length) + { + url = args[i + 1]; + } + } + + if (string.IsNullOrWhiteSpace(url)) + { + url = Environment.GetEnvironmentVariable("YUNCANG_SERVER"); + } + + _settings.UseServer(url); + } + /// 显示登录窗;返回 false = 用户取消(应退出程序) private bool ShowLogin() { diff --git a/desktop/LoginWindow.xaml b/desktop/LoginWindow.xaml index 3b7410e..14c6dcc 100644 --- a/desktop/LoginWindow.xaml +++ b/desktop/LoginWindow.xaml @@ -16,8 +16,13 @@ FontSize="12" Foreground="{StaticResource MutedBrush}" HorizontalAlignment="Center" Margin="0,6,0,18" /> - - + + + + + + diff --git a/desktop/LoginWindow.xaml.cs b/desktop/LoginWindow.xaml.cs index edb35ff..20d25a1 100644 --- a/desktop/LoginWindow.xaml.cs +++ b/desktop/LoginWindow.xaml.cs @@ -36,6 +36,10 @@ public partial class LoginWindow : Window AccountBox.Text = settings.LastAccount; RememberBox.IsChecked = settings.RememberAccount; + // 环境由构建决定(Debug = 开发环境,Release = 生产环境),默认地址也来自构建 + EnvText.Text = BuildInfo.EnvironmentLabel; + ServerBox.ToolTip = $"留空即使用{BuildInfo.EnvironmentLabel}默认地址:{BuildInfo.DefaultServer}\n启动时可用 --server=http://x.x.x.x:7300 临时指定"; + Loaded += OnLoaded; } diff --git a/desktop/README.md b/desktop/README.md index 1377d6b..9357574 100644 --- a/desktop/README.md +++ b/desktop/README.md @@ -42,32 +42,63 @@ desktop/ | 再次双击 exe / 点网页「启动本机软件」 | 不会开第二个:把 `yuncang://open?code=…` 通过命名管道转给已运行实例 | | 托盘双击 / 右键「打开主界面」 | 恢复窗口 | | 「退出登录」 | 清令牌 → 关闭主窗口 → 回到登录页(取消登录则退出程序) | +| 网页请求唤起登录(`POST /api/activate-login`) | 未登录:登录窗弹到最前;已登录:主界面弹到最前(不影响本机服务) | | 托盘右键「退出」 | 真正退出(dispose 托盘与本机服务) | -服务器地址默认 `http://127.0.0.1:7300`(后端 dev 默认端口),登录页上可以改,改完会存进 `settings.json`。 -换服务器后不会复用旧令牌(会要求重新登录)。 +## 环境配置(开发 / 生产) + +和前端 `VITE_BACKEND` 一个思路:**由构建决定,不靠用户手填**。 + +| 构建 | `env` | 默认后端 | +| --- | --- | --- | +| `dotnet build`(Debug) | `Development` | `http://127.0.0.1:7300`(= 前端 dev 代理的后端) | +| `dotnet build -c Release` | `Production` | `https://packs.example.com`(占位,打包时必须覆盖) | + +打包正式版时指定真实域名: + +```powershell +dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com -o publish +``` + +优先级(从高到低): + +1. 启动参数 `--server=http://192.168.1.10:7300`(临时,不落盘); +2. 环境变量 `YUNCANG_SERVER`; +3. `-p:ServerBaseUrl=` 注入的构建默认值; +4. 用户在登录页手改并保存的地址(`settings.json`)。 + +几个细节: + +- 地址等于**内置默认值**时,`settings.json` 里存空串 —— 所以换 Debug/Release 构建能自动跟随, + 不会被上一次构建的默认值钉死;只有用户手改过的地址才会持久化。 +- 换地址后**不会复用旧令牌**(`session.json` 里的 `ServerBaseUrl` 对不上就要求重新登录)。 +- `GET /api/health` 会回 `env` 和 `server`,排查环境是否装错时先看这两个字段。 ## 环境要求 - 编译:**.NET 8 SDK**(`dotnet --list-sdks` 能看到 `8.x`) - 只运行已发布的 exe:**.NET 8 Desktop Runtime**(不需要 SDK) -> 本仓库当前环境**没有装 .NET**,所以这份代码没在 CI 里编译过;第一次请自己跑一遍 -> `dotnet build`,有报错直接贴出来。 +> 本机 SDK 装在用户目录(免管理员):`%LOCALAPPDATA%\Microsoft\dotnet`, +> 已加入用户 `PATH` 和 `DOTNET_ROOT`。**新开的终端**才能直接用 `dotnet`; +> 老终端里临时用:`$env:DOTNET_ROOT="$env:LOCALAPPDATA\Microsoft\dotnet"; $env:Path="$env:DOTNET_ROOT;$env:Path"`。 +> 直接双击 `bin\...\*.exe` 也需要 `DOTNET_ROOT` 已生效(否则报 “You must install .NET”)。 +> 官方安装包:`winget install --id Microsoft.DotNet.SDK.8 -e`(要 UAC)。 ## 构建 / 运行 / 发布 ```powershell cd desktop -dotnet build -c Release # 编译 -dotnet run # 直接跑(调试) +dotnet build # 编译(Debug = 开发环境,连本地 7300) +dotnet build -c Release # 编译(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 -p:ServerBaseUrl=https://trace.example.com --self-contained false -o publish # 或者自带运行时(体积大,但用户什么都不用装) -dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -o publish +dotnet publish -c Release -r win-x64 -p:ServerBaseUrl=https://trace.example.com --self-contained true -p:PublishSingleFile=true -o publish ``` ## 本机接口(前端 `/local` 页用的就是这三个) @@ -80,7 +111,7 @@ dotnet publish -c Release -r win-x64 --self-contained true -p:PublishSingleFile= | 方法 | 路径 | 说明 | | --- | --- | --- | -| GET | `/api/health` | 验活 + 登录状态:**2xx 即认为软件已启动**。返回 `{ ok, name, version, port, loggedIn, user, serverTime }` | +| GET | `/api/health` | 验活 + 登录状态:**2xx 即认为软件已启动**。返回 `{ ok, name, version, port, env, server, loggedIn, user, serverTime }`(`env` = `Development`/`Production`) | | GET | `/api/query/{code}` | 按运单号查信息(**需已登录**,否则 401 `{ ok:false, loggedIn:false, message }`)。成功时字段**平铺**在顶层(`{ code, orderNo, ... }`) | | POST | `/api/activate-login` | 把本机软件的**登录窗叫到前台**(已登录时把主界面叫到前台)。网页发现 `loggedIn:false` 时自动调它 | diff --git a/desktop/Services/AppSettings.cs b/desktop/Services/AppSettings.cs index 398c314..ccdcef0 100644 --- a/desktop/Services/AppSettings.cs +++ b/desktop/Services/AppSettings.cs @@ -9,15 +9,21 @@ namespace YuncangTrace.LocalService.Services; /// 本机设置:`%LOCALAPPDATA%\YuncangTrace\settings.json` /// /// 目前只有「服务器地址」(登录用的后端)和「记住账号」。 +/// 服务器地址的**默认值**来自构建环境(),用户没改过就不落盘, +/// 这样 Debug / Release 两个构建各自连自己的后端,不会互相污染。 /// public sealed class AppSettings { - /// 默认后端地址(本地开发) - public const string DefaultServer = "http://127.0.0.1:7300"; + /// 当前构建的默认后端地址(Debug = 本地 7300,Release = 正式站点) + public static string DefaultServer => BuildInfo.DefaultServer; /// 后端 API 根地址(登录、校验令牌都走它) public string ServerBaseUrl { get; set; } = DefaultServer; + /// 地址来自命令行/环境变量的临时覆盖(不落盘) + [System.Text.Json.Serialization.JsonIgnore] + public bool ServerIsVolatile { get; private set; } + /// 上次登录的账号(只在「记住账号」勾选时保存) public string LastAccount { get; set; } = string.Empty; @@ -45,7 +51,10 @@ public sealed class AppSettings var settings = JsonSerializer.Deserialize(File.ReadAllText(FilePath)); if (settings is null) return new AppSettings(); - settings.ServerBaseUrl = Normalize(settings.ServerBaseUrl); + // 文件里存的是空串 = 用户没改过,用当前构建的默认值; + // 老版本会把默认地址直接落盘,所以「等于任何已知默认值」也当作没改过,跟随当前构建。 + var stored = Normalize(settings.ServerBaseUrl); + settings.ServerBaseUrl = IsKnownDefault(stored) ? DefaultServer : stored; return settings; } catch (Exception ex) @@ -55,6 +64,17 @@ public sealed class AppSettings } } + /// 运行时指定后端地址(--server= / YUNCANG_SERVER),只影响本次运行 + public void UseServer(string? url) + { + var value = (url ?? string.Empty).Trim(); + if (value.Length == 0) return; + + ServerBaseUrl = Normalize(value); + ServerIsVolatile = true; + AppLog.Write($"后端地址已被临时覆盖:{ServerBaseUrl}(不保存)"); + } + /// 存设置(失败只记日志) public void Save() { @@ -64,7 +84,17 @@ public sealed class AppSettings if (!RememberAccount) LastAccount = string.Empty; Directory.CreateDirectory(Dir); - File.WriteAllText(FilePath, JsonSerializer.Serialize(this, Options)); + + // 等于构建默认值(或只是临时覆盖)就写空串:换环境构建时能自动跟随,只有用户手改的地址才落盘 + var stored = ServerIsVolatile || ServerBaseUrl == DefaultServer ? string.Empty : ServerBaseUrl; + var payload = new StoredSettings + { + ServerBaseUrl = stored, + LastAccount = LastAccount, + RememberAccount = RememberAccount, + }; + + File.WriteAllText(FilePath, JsonSerializer.Serialize(payload, Options)); } catch (Exception ex) { @@ -81,4 +111,22 @@ public sealed class AppSettings if (!value.Contains("://", StringComparison.Ordinal)) value = "http://" + value; return value.TrimEnd('/'); } + + /// 是不是"内置默认地址"之一(老版本落盘过这些值,不该当成用户自定义) + private static bool IsKnownDefault(string url) + { + return url.Equals(DefaultServer, StringComparison.OrdinalIgnoreCase) + || url.Equals(Normalize(BuildInfo.DevServer), StringComparison.OrdinalIgnoreCase) + || url.Equals(Normalize(BuildInfo.ProdServerPlaceholder), StringComparison.OrdinalIgnoreCase); + } + + /// 落盘用的结构(和本类的可读属性一一对应) + private sealed class StoredSettings + { + public string ServerBaseUrl { get; set; } = string.Empty; + + public string LastAccount { get; set; } = string.Empty; + + public bool RememberAccount { get; set; } = true; + } } diff --git a/desktop/Services/BuildInfo.cs b/desktop/Services/BuildInfo.cs new file mode 100644 index 0000000..faeba19 --- /dev/null +++ b/desktop/Services/BuildInfo.cs @@ -0,0 +1,63 @@ +using System; +using System.Linq; +using System.Reflection; + +namespace YuncangTrace.LocalService.Services; + +/// +/// 构建期注入的环境信息 —— 和前端 VITE_BACKEND 一个思路: +/// 开发 / 生产由**构建**决定,不靠用户手填。 +/// +/// - Debug 构建 :环境 = Development,默认后端 http://127.0.0.1:7300(与前端 dev 代理一致); +/// - Release 构建 :环境 = Production,默认后端 https://packs.example.com(占位,打包时覆盖); +/// - 打包时覆盖 :dotnet build -c Release -p:ServerBaseUrl=https://你的域名。 +/// +/// 值由 YuncangTrace.LocalService.csproj 通过 写进程序集, +/// 因此 exe 自己就带着"它是哪个环境"的信息,不需要额外的配置文件。 +/// +public static class BuildInfo +{ + /// Debug 构建的默认后端(= 前端 dev 代理的后端 127.0.0.1:7300) + public const string DevServer = "http://127.0.0.1:7300"; + + /// Release 构建的默认后端(占位,打包时用 -p:ServerBaseUrl= 覆盖) + public const string ProdServerPlaceholder = "https://packs.example.com"; + + /// 环境名:Development / Production + public static string Environment { get; } = ReadMetadata("AppEnvironment", "Development"); + + /// 当前构建的默认后端地址 + public static string DefaultServer { get; } = Normalize(ReadMetadata("ServerBaseUrl", DevServer)); + + /// 是不是开发(Debug)构建 + public static bool IsDevelopment => + Environment.Equals("Development", StringComparison.OrdinalIgnoreCase); + + /// 给人看的环境名(登录窗里显示) + public static string EnvironmentLabel => IsDevelopment ? "开发环境" : "生产环境"; + + /// --server=... / YUNCANG_SERVER 的运行时覆盖(排在构建默认值之前) + private static string ReadMetadata(string key, string fallback) + { + try + { + var value = Assembly.GetEntryAssembly() + ?.GetCustomAttributes() + .FirstOrDefault(a => string.Equals(a.Key, key, StringComparison.OrdinalIgnoreCase)) + ?.Value; + + return string.IsNullOrWhiteSpace(value) ? fallback : value.Trim(); + } + catch + { + return fallback; + } + } + + private static string Normalize(string url) + { + var value = url.Trim(); + if (!value.Contains("://", StringComparison.Ordinal)) value = "http://" + value; + return value.TrimEnd('/'); + } +} diff --git a/desktop/Services/LocalHttpServer.cs b/desktop/Services/LocalHttpServer.cs index 764970b..8abef12 100644 --- a/desktop/Services/LocalHttpServer.cs +++ b/desktop/Services/LocalHttpServer.cs @@ -46,6 +46,9 @@ public sealed class LocalHttpServer : IDisposable /// 当前登录用户显示名(由 App 提供,供 `/api/health` 用) public Func? UserNameProvider { get; set; } + /// 当前后端地址(由 App 提供,供 `/api/health` 排障用) + public Func? ServerBaseUrlProvider { get; set; } + public LocalHttpServer(OrderQueryService queryService) { _queryService = queryService; @@ -173,6 +176,8 @@ public sealed class LocalHttpServer : IDisposable name = "云仓视频溯源打印服务", version = typeof(LocalHttpServer).Assembly.GetName().Version?.ToString() ?? "1.0.0", port = Port, + env = BuildInfo.Environment, + server = ServerBaseUrlProvider?.Invoke(), loggedIn = IsLoggedIn, user = UserNameProvider?.Invoke(), serverTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), diff --git a/desktop/Services/ProtocolHelper.cs b/desktop/Services/ProtocolHelper.cs index 6dd59ca..55b550e 100644 --- a/desktop/Services/ProtocolHelper.cs +++ b/desktop/Services/ProtocolHelper.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; using Microsoft.Win32; diff --git a/desktop/YuncangTrace.LocalService.csproj b/desktop/YuncangTrace.LocalService.csproj index 9f76eaa..13cd22f 100644 --- a/desktop/YuncangTrace.LocalService.csproj +++ b/desktop/YuncangTrace.LocalService.csproj @@ -24,6 +24,24 @@ YuncangTrace.LocalService app.manifest + + $(NoWarn);WFAC010 + + + Development + Production + http://127.0.0.1:7300 + https://packs.example.com + 1.0.0 云仓视频溯源软件 云仓 @@ -31,4 +49,16 @@ zh-CN + + + + <_Parameter1>AppEnvironment + <_Parameter2>$(AppEnvironment) + + + <_Parameter1>ServerBaseUrl + <_Parameter2>$(ServerBaseUrl) + + +