You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET8 MAUI在Windows中使用SecureStorage保存空值报错问题

.NET 8 MAUI SecureStorage Windows端存空字符串报错问题

这是Windows平台SecureStorage实现的预期行为,根源在于不同平台的底层存储API规则存在差异:

  • Android端的SecureStorage基于SharedPreferences实现,该API支持存储空字符串;
  • Windows端则依赖ApplicationData.Current.LocalSettings,这个Windows原生API明确禁止存储空值,传入空字符串就会抛出ArgumentException。

解决方案

你可以在保存前做空值判断,避免传入空字符串:

  1. 如果空值代表"无数据",直接调用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);
  1. 如果需要保留键但标记为空,可以用一个占位符(比如"__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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 04:17:01