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

使用Newtonsoft将List数据写入JSON文件失败求助

问题诊断与解决方案

1. 按钮事件绑定错误(直接导致无响应的核心问题)

你的Razor页面中Save按钮的事件绑定写法错误,Blazor中需使用@onclick而非onclick,否则点击按钮不会触发saveData方法:

<!-- 错误写法 -->
<button onclick="@saveData">Save</button>

<!-- 正确写法 -->
<button @onclick="@saveData">Save</button>

2. 文件路径与权限问题

确保目标目录存在

C:\Data\目录可能尚未创建,File.CreateText会因目录不存在抛出异常,需先判断并创建目录:

public void SavetoJson(string filename, List<T> dataList)
{
    string directoryPath = @"C:\Data\";
    // 先创建目录(不存在则创建)
    if (!Directory.Exists(directoryPath))
    {
        Directory.CreateDirectory(directoryPath);
    }
    
    using (StreamWriter file = File.CreateText(Path.Combine(directoryPath, filename)))
    {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, dataList);
    }
}

适配Blazor运行环境权限

  • Blazor Server:确保应用池运行账户(如IIS AppPool\你的应用池名称)拥有C:\Data\的写入权限;
  • Blazor WebAssembly:浏览器沙箱禁止直接访问本地磁盘,需改为通过浏览器下载文件:
private void saveData()
{
    var json = JsonConvert.SerializeObject(_userRoles);
    var bytes = System.Text.Encoding.UTF8.GetBytes(json);
    var base64 = Convert.ToBase64String(bytes);
    var downloadUrl = $"data:application/json;base64,{base64}";

    // 触发浏览器下载
    var anchor = new ElementReference();
    anchor.SetAttribute("href", downloadUrl);
    anchor.SetAttribute("download", "userRoles.json");
    anchor.ClickAsync();
}

3. 添加异常捕获,定位错误根源

在saveData方法中加入异常捕获,直接显示错误信息,快速排查问题:

private void saveData()
{                
    try
    {
        SaveData<User_Role> _data = new SaveData<User_Role>();
        _data.SavetoJson("userRoles.json",_userRoles);
        _confirmation = "数据保存成功";
    }
    catch (Exception ex)
    {
        _confirmation = $"保存失败:{ex.Message}";
    }
}

4. 序列化兼容性处理

User_Role类包含List<User>属性,但未提供User类定义。若User类不可序列化(如无无参构造函数、包含不可序列化属性),会导致序列化失败。若暂时不需要序列化该列表,可添加[JsonIgnore]标记:

public class User_Role
{
    public string RoleId { get; init; }
    public string RoleName { get; set; }
    public string RoleDescription { get; set; }
    [JsonIgnore] // 忽略该属性,避免序列化报错
    public List<User> Users { get; set; }

    // 构造函数...
}

5. 优化角色存在检查逻辑

你的roleExists方法可通过LINQ简化,同时避免逻辑漏洞:

private bool roleExists(List<User_Role> user_Roles, string currentRoleName)
{
    return user_Roles?.Any(item => item?.RoleName == currentRoleName) ?? false;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:07:13