c# - 如何在 ASP.NET Core 中使用 XML 或 JSON 作为数据源

标签 c# asp.net json xml

<分区>

我想使用 JSON 或 XML 文件将我的数据存储在 ASP.NET 核心应用程序中。
这样做的原因是数据不多,数据变化不大。优点是提高了应用程序的速度,而且我不需要应用程序的数据库(省钱)。

所以我的想法是将数据序列化为 XML 或 JSON。当应用程序启动时,这些数据应该加载到内存中。
在更改时应更新文件。

是否有一种直接的方法可以做到这一点,或者这种工作方式是否应该被劝阻?

最佳答案

无论您决定使用哪种数据存储技术,我都建议您将数据访问抽象为某些接口(interface),这样您的应用程序就不会绑定(bind)到特定的实现。如果您将来决定这样做,这将使您能够更轻松地切换到其他一些存储技术。

因此,如果您想使用内存数据存储,那为什么不呢:

public interface IDataStore
{
    IQueryable<MyModel> Get();

    void Add(MyModel model);

    ...
}

可以这样实现:

public JsonDatastore : IDataStore
{
    private readonly string dataFile;
    private readonly IList<MyModel> data;

    public Datastore(string dataFile)
    {
        this.dataFile = dataFile;
        this.data = JsonConvert.DeserializeObject<IList<MyModel>>(File.ReadAllText(dataFile));
    }

    public IQueryable<MyModel> Get()
    {
        return this.data.AsQueryable();
    }

    public void Add(MyModel model)
    {
        // If you want a lock free implementation you may consider
        // an algorithm which will only notify some underlying thread
        // that a change has been made to the underlying structure and
        // it will take care of saving those changes to the file system
        // This way it is guaranteed that only one thread is writing
        // to the file while the changes can be made in memory quite fast
        // (using a ConcurrentBag<T> instead of a list for example)

        lock (this)
        {
            // Make sure that only one thread is updating the file
            this.data.Add(model);
            string json = JsonConvert.SerializeObject(this.data);
            File.WriteAllText(this.dataFile, json);
        }
    }
}

现在最后一个重要的一点是确保将依赖注入(inject)容器中的 Datastore 生命周期实例配置为 singleton

关于c# - 如何在 ASP.NET Core 中使用 XML 或 JSON 作为数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41651897/

相关文章:

ASP.NET 压缩

android - JSONObject 响应为空

c# - 如何在 .NET 4.x 中强制进行完全垃圾回收?

c# - 为什么我需要从 ConcurrentDictionary 转换为 Dictionary 才能使用 Add()?

javascript - 我们能确定MVC EnableCors的由来吗?

c# - ASP.NET 中的字典查找效率和请求范围全局变量?可通过 global.asax 和页面/等访问

javascript - 从公共(public)文件夹中 Fetch() 本地 json 文件返回 HTML 文件

android - 读取 SharedPreferences 中的自定义 ArrayList 调用运行时异常

c# - 系统.Data.SqlClient.SqlException : Incorrect syntax near the keyword 'file'

c# - 调试器无法继续运行该进程。无法开始调试