使用 web.config 中的连接字符串而不是 app.config

发布于 2024-10-16 21:34:37 字数 760 浏览 4 评论 0原文

我有一个类库项目,其中添加了一个与 sql server 通信的数据集。该项目的输出将从 Web 应用程序项目中使用。所以我打算将我的连接字符串放在Web应用程序项目中。

做了几件事。为了使我的适配器使用不同的连接字符串,我遇到了 这个。但我最终发现执行以下操作很方便:

Dim adapter as New MyReqeustTableAdapter()
adapter.Connection.ConnectionString = sMyConnectionString

然后我尝试将连接字符串从我的配置(app.config)中获取到模拟。我使用键“myconstr”手动添加了一个部分。我的想法是做类似的事情:

sMyConnectionString = ConfigurationManager.ConnectionString("myconstr").ConnectionString

但我的智能感知无法检测到 ConfigurationManager。因此必须添加对项目的适当引用。

接下来,我通过 Web 应用程序项目的设置设计器添加了一个连接字符串。我给出了上面的密钥以供参考。然而上面的语句似乎抛出了一个空引用异常。

I have a class library project in which I've added a dataset which talks with sql server. The output of this project is to be consumed from a web application project. So I intend to put my connection string in the web application project.

Did a couple of things. In order to make my adapter use a different connection string, I had come across this. But I finally found doing the following convenient:

Dim adapter as New MyReqeustTableAdapter()
adapter.Connection.ConnectionString = sMyConnectionString

Then I tried taking the connection string from my configuration (app.config) to kind of simulate . I added a section manually with key "myconstr". My ideas was to do something like:

sMyConnectionString = ConfigurationManager.ConnectionString("myconstr").ConnectionString

But my intellisense couldn't not detect ConfigurationManager. So had to add the appropriate reference to the project.

Next I added a connection string via the settings designer for the web application project. I gave the above key for referencing it. However the above statment seems to throw a null reference exception.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

风为裳 2024-10-23 21:34:38

假设您已经创建了一个类库。在其中您定义了一个设置属性,如下所示:

Properties.Settings.Default.ProjectName

Visual Studio 可能会自动为您生成一些配置,如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="MyDllProject.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <MyDllProject.Properties.Settings>
            <setting name="ProjectName" serializeAs="String">
                <value>MyDllproject</value>
            </setting>
        </MyDllProject.Properties.Settings>
    </applicationSettings>
</configuration>

(app.config)
现在 假设您将此程序集添加到项目中。当您访问它的设置时,您很可能会得到 MyDllproject 作为它的值。尽管添加了任何配置,但这还是如此。为什么?因为当生成程序集时,它就被写入其中了。编写的代码是这样的,在没有配置覆盖的情况下,使用生成时在 app.config 中定义的内容。

现在,在您的目标项目中,您只需按照以下模式在配置文件中添加必要的部分即可

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>

        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <!-- start: copied from app.config of class library -->
            <section name="MyDllProject.Properties.Settings" 
                type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" 
                />
            <!-- end: copied from app.config of class library -->

            <!-- other sections may follow -->
        </sectionGroup>

    </configSections>

    <applicationSettings>
        <!-- remember to maintain the same order as how it was defined in the sectionGroup -->

        <!-- start: copied from app.config of class librarly -->
        <MyDllProject.Properties.Settings>
            <setting name="ProjectName" serializeAs="String">
                <value>ConsoleProjectB</value>
            </setting>
        </MyDllProject.Properties.Settings>
        <!-- end: copied from app.config of class library -->

        <!-- other configurations settings may follow -->
    </applicationSettings>
</configuration>

这是我链接到的一个小项目示例:http://sdrv.ms/16ksPef

Suppose you have created a class library. In it you've defined a Settings property which goes like:

Properties.Settings.Default.ProjectName

Visual Studio might auto generate some configuration for you as follows:

(app.config) 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <section name="MyDllProject.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        </sectionGroup>
    </configSections>
    <applicationSettings>
        <MyDllProject.Properties.Settings>
            <setting name="ProjectName" serializeAs="String">
                <value>MyDllproject</value>
            </setting>
        </MyDllProject.Properties.Settings>
    </applicationSettings>
</configuration>

Now say you add this assembly to an project. And you access its settings, you'd most probably get MyDllproject as it value. This is in spite of adding any configuration. Why? Because when the assembly was generated it was kind of written into it. And the code written is such that in the absence of a configuration override use what was defined in the app.config at the time of generation.

Now in your target project, you simply add the necessary sections in the configuration file in the following pattern

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>

        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
            <!-- start: copied from app.config of class library -->
            <section name="MyDllProject.Properties.Settings" 
                type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" 
                />
            <!-- end: copied from app.config of class library -->

            <!-- other sections may follow -->
        </sectionGroup>

    </configSections>

    <applicationSettings>
        <!-- remember to maintain the same order as how it was defined in the sectionGroup -->

        <!-- start: copied from app.config of class librarly -->
        <MyDllProject.Properties.Settings>
            <setting name="ProjectName" serializeAs="String">
                <value>ConsoleProjectB</value>
            </setting>
        </MyDllProject.Properties.Settings>
        <!-- end: copied from app.config of class library -->

        <!-- other configurations settings may follow -->
    </applicationSettings>
</configuration>

Thats it.

Here is a small project sample I've linked to for the same: http://sdrv.ms/16ksPef

待"谢繁草 2024-10-23 21:34:38

您可以添加对 System.Web 的引用并使用类库项目中的 System.Web.Configuration.WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString)

you can add reference to System.Web and use System.Web.Configuration.WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString) from the class library project

枕头说它不想醒 2024-10-23 21:34:38

类库项目中定义的配置文件(app.config)不能被系统自动使用。唯一可以使用的配置文件是 Web 应用程序中的 web.config 文件或 exe 应用程序中的 *myexe.exe*.config,其中 exe 文件是 * myexe.exe*

所以您似乎正在尝试将 app.config 添加到类库中。那是行不通的。

可以将第二个配置文件链接到 web.config 但这可能对您没有帮助。

A configuration file (app.config) which is defined in a class library project cannot be - automatically - consumed by the system. The only config file that can be consumed is the web.config file in web applications or *myexe.exe*.config in exe applications where exe file is *myexe.exe*.

So you seem to be trying to add app.config to the class library. That ain't gonna work.

It is possible to link a second config file to the web.config but that probbaly is no help to you.

清风挽心 2024-10-23 21:34:38

基本上,您需要的是能够从外部更改库的全局参数。单独使用 app.config 并不能立即为您提供这种可能性——您还没有公开您的库内部设置。考虑到这一点,实现曝光的一种非常简单的方法是在您的库中为 app.config 创建一个分配器。

public static class Setter
{
    public static void Set(string name, string value)
    {
        Properties.Settings.Default[name] = value;
    }
}

然后,在 web 应用程序中从 global.asax 或其他地方启动:

MyLibrary.Setter.Set("X", ConfigurationManager.ConnectionStrings["Y"].ConnectionString);

Basically, what you need is a possibility to change a global parameter of your library from outside. Using app.config by itself does not give you that possibility straight away -- you have not exposed your library internal settings yet. With that in mind, one very straightforward way to achieve exposure is to create in your library an assigner for the app.config.

public static class Setter
{
    public static void Set(string name, string value)
    {
        Properties.Settings.Default[name] = value;
    }
}

Then, at web application start in global.asax, or elsewhere:

MyLibrary.Setter.Set("X", ConfigurationManager.ConnectionStrings["Y"].ConnectionString);
飘然心甜 2024-10-23 21:34:38

从你的问题来看,我认为你正在构建一个 n 层应用程序。我认为你提到的两种选择更好。

您应该只为 DAL(数据访问层)类创建一个基类,该类将具有包含连接字符串的公共属性。

顺便说一句,它将帮助您隐藏/保护您的连接字符串,而不是将其存储在任何拥有或已获得主机访问权限的人都可以轻松读取的文件中

 公共类 DALBase
 {
     公共静态字符串 connString
     {
         get { return "数据源=localhost\\SqlExpress;初始目录=theDb Integrated Security=True"; }
     }
 }

From your question I think you're building an n-layered application. I think you're better off the two options you mentioned.

You should just create a base class for your DAL (Data Access Layer) classes that will have a public property that contains that the connection string.

btw it will help you hide/secure your connection string instead of storing it in a file that could be easily read by anyone who have or gained access to your host

 public class DALBase
 {
     public static string connString
     {
         get { return "Data Source=localhost\\SqlExpress;Initial Catalog=theDb Integrated Security=True"; }
     }
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文