如何将数据从配置文件存储在类中,并在整个项目的运行时读取它们



我正在开发一个asp.Net MVC web应用程序,在项目的一个文件夹下,我有几个XML配置文件,每个文件都用于特定的客户端。我需要做的是在运行时,我需要根据URL读取特定的xml文件,并将文件值保存到一个类中,然后读取所有类中的这些属性。换句话说,如果我有这两个xml文件:firstCompany.xmlsecondCompany.xml,并且url是www.firstCompany.com,那么我需要从firstCmompany.xml读取,然后将所有值存储在一个类中,该类可以在应用程序中的所有类中使用。

您可以用数据填充类对象,然后将该数据对象放置在会话中。

然后,您可以在控制器或视图中的任何位置访问该对象。只有当会话还活着的时候。

最好的方法是创建一个static类,并在其中添加所需的信息作为属性。在启动时,您可以填充这些属性,并在需要的时候调用它们,当然无需初始化类。例如:

public static class My_Page_Base
{
    private static RequestContext _RequestContext;
    public static RequestContext RequestContext
    {
        get { return _RequestContext; }
        set { _RequestContext = value; }
    }
    private static string _connectionString;
    public static string connectionString
    {
        get { return _connectionString; }
        set { _connectionString = value; }
    }
}

当你需要设置或获取这些属性时,你只需要如下调用它们:

// set the connection string property
My_Page_Base.connectionString = "you set here the connection string";
// get the connection string property
string conStr = My_Page_Base.connectionString;

最新更新