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

如何在.NET8 Android Blazor Hybrid App中持久化存储用户数据?

.NET 8 Blazor Hybrid Android 应用数据持久化最佳实践

针对Blazor Hybrid(Android平台)的轻量用户数据(字符串、布尔值、设置项)持久化,以下是几种标准且实用的方案,按场景推荐:

1. Preferences API(首选轻量键值对)

适合存储零散的配置项、开关状态、简单字符串这类数据,是.NET MAUI提供的跨平台API,Android端底层会映射到SharedPreferences,无需额外权限。

使用步骤:

  1. 引用Microsoft.Maui.Storage命名空间
  2. 存储数据:
// 保存用户名
Preferences.Set("UserName", "Konrad");
// 保存深色模式开关
Preferences.Set("DarkModeEnabled", true);
  1. 读取数据:
// 读取,第二个参数是默认值
var userName = Preferences.Get("UserName", string.Empty);
var isDarkMode = Preferences.Get("DarkModeEnabled", false);

2. 本地JSON文件存储(适合结构化数据)

如果需要存储一组关联的用户数据(比如完整的用户设置对象),可以将对象序列化为JSON后保存到本地文件,存储路径推荐用应用私有目录,避免权限问题。

使用示例:

using System.Text.Json;
using Microsoft.Maui.Storage;

// 定义用户设置实体
public class AppUserSettings
{
    public string Nickname { get; set; }
    public bool EnableNotifications { get; set; }
    public int FontSize { get; set; }
}

// 保存数据
var settings = new AppUserSettings 
{ 
    Nickname = "Konrad", 
    EnableNotifications = true, 
    FontSize = 16 
};
string jsonContent = JsonSerializer.Serialize(settings);
string savePath = Path.Combine(FileSystem.AppDataDirectory, "user_settings.json");
File.WriteAllText(savePath, jsonContent);

// 读取数据
if (File.Exists(savePath))
{
    string loadedJson = File.ReadAllText(savePath);
    var loadedSettings = JsonSerializer.Deserialize<AppUserSettings>(loadedJson);
}

3. SQLite数据库(适合复杂/关联数据)

如果需要存储大量结构化、有关联关系的数据(比如用户的多条记录),SQLite是最佳选择,推荐使用SQLite-net-pcl这个轻量ORM库。

使用步骤:

  1. 安装NuGet包:SQLite-net-pcl
  2. 定义实体类:
using SQLite;

public class UserRecord
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string Content { get; set; }
    public DateTime CreatedAt { get; set; }
    public bool IsFavorite { get; set; }
}
  1. 数据库操作:
// 初始化数据库连接
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "app_database.db");
var db = new SQLiteConnection(dbPath);
// 创建表
db.CreateTable<UserRecord>();

// 插入数据
db.Insert(new UserRecord 
{ 
    Content = "我的第一条记录", 
    CreatedAt = DateTime.Now, 
    IsFavorite = true 
});

// 查询数据
var favoriteRecords = db.Table<UserRecord>().Where(r => r.IsFavorite).ToList();

敏感数据处理

如果要存储密码、令牌这类敏感信息,绝对不能用上面的普通方案,应该使用SecureStorage API,它在Android端会借助系统Keystore加密存储:

// 存储敏感数据
await SecureStorage.SetAsync("UserAuthToken", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...");

// 读取敏感数据
var authToken = await SecureStorage.GetAsync("UserAuthToken");

注意事项

  • 尽量使用FileSystem.AppDataDirectory作为存储路径,这是应用的私有目录,无需申请Android存储权限,且卸载应用时会自动清理。
  • 对于频繁读写的数据,优先用Preferences或SQLite,避免频繁文件IO影响性能。

内容的提问来源于stack exchange,提问作者Konrad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 23:33:29