.NET8 MAUI在Windows中使用SecureStorage保存空值报错问题
.NET 8 MAUI SecureStorage Windows端存空字符串报错问题
这是Windows平台SecureStorage实现的预期行为,根源在于不同平台的底层存储API规则存在差异:
- Android端的SecureStorage基于SharedPreferences实现,该API支持存储空字符串;
- Windows端则依赖
ApplicationData.Current.LocalSettings,这个Windows原生API明确禁止存储空值,传入空字符串就会抛出ArgumentException。
解决方案
你可以在保存前做空值判断,避免传入空字符串:
- 如果空值代表"无数据",直接调用
RemoveAsync删除对应键:
if (string.IsNullOrEmpty(login.UserId)) { await SecureStorage.Default.RemoveAsync("userId"); } else { await SecureStorage.Default.SetAsync("userId", login.UserId); } await SecureStorage.Default.SetAsync("username", login.UserName);
- 如果需要保留键但标记为空,可以用一个占位符(比如
"__EMPTY__"),读取时再转换回空字符串:
var userIdValue = string.IsNullOrEmpty(login.UserId) ? "__EMPTY__" : login.UserId; await SecureStorage.Default.SetAsync("userId", userIdValue); // 读取时 var storedUserId = await SecureStorage.Default.GetAsync("userId"); var actualUserId = storedUserId == "__EMPTY__" ? string.Empty : storedUserId;
内容的提问来源于stack exchange,提问作者Enrico
相关产品推荐
相关产品推荐

