经典Win32微软商店应用离线时StoreContext.GetAppLicenseAsync无法返回缓存许可证的问题
经典Win32微软商店应用离线时StoreContext.GetAppLicenseAsync无法返回缓存许可证的问题
我最近碰到一个挺棘手的问题:开发的经典Win32应用发布到微软商店后,启动时会做产品许可证状态检查,在线时一切正常,但离线状态下StoreContext.GetAppLicenseAsync()没法返回本地缓存的许可证,导致授权验证直接失败。
先贴一下我目前用的核心C++/WinRT代码片段:
#include <Windows.Foundation.h> #include <Windows.System.h> #include <Windows.Services.Store.h> enum class LicenseStatus { none, error, valid, }; void Init() { winrt::init_apartment(); } LicenseStatus GetAppLicenseStatus() { using namespace winrt::Windows::Services::Store; try { if (auto storeContext = StoreContext::GetDefault()) { if (auto storeProductRes = storeContext.GetStoreProductForCurrentAppAsync().get()) { if (auto storeProduct = storeProductRes.Product()) { if (auto appLicense = storeContext.GetAppLicenseAsync().get()) { if (appLicense.IsActive()) { return LicenseStatus::valid; } } } } } } catch (const winrt::hresult_error& ex) { // 离线时会触发这里,但期望是读取缓存而不是报错 return LicenseStatus::error; } return LicenseStatus::none; }
这段代码在线环境下能顺利获取到激活状态的许可证,但离线时要么在GetAppLicenseAsync().get()这里卡住,要么直接抛出网络相关的异常,完全没用到本地缓存的许可证——按微软商店的授权逻辑,离线时应该优先读取本地缓存才对。
后来我梳理了几个可能的解决方向,分享给大家:
- 首先要确保应用至少在线成功验证过一次许可证,系统才会生成并保存本地缓存,没在线验证过的话肯定没有缓存可用
- 检查
StoreContext的初始化是否正确,Win32应用里要确保它关联到当前登录的微软商店用户会话,别用错了上下文 - 异常捕获要更细致,区分是网络错误还是真的许可证无效,比如捕获
hresult_error后查看具体错误码,如果是WININET_E_NAME_NOT_RESOLVED这类网络错误,可以针对性处理,尝试触发缓存读取逻辑 - 另外,应用清单里要确认添加了必要的权限:
internetClient是必须的(首次在线验证需要),如果是内网环境可能还要加privateNetworkClientServer
调试时可以先在线启动一次应用,确认许可证缓存已生成,然后断网测试,同时打印异常的具体错误信息,能更快定位问题。
备注:内容来源于stack exchange,提问作者josuegomes
相关产品推荐
相关产品推荐

