在web.config中放置连接字符串的位置

时间:2014-11-12 08:48:28

标签: c# asp.net-mvc connection-string

我的web.config看起来像这样:

<configuration>

  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <runtime>

当我在<configuration>下面添加我的连接字符串时,我收到一条错误消息,指出只允许一个<configSections>元素。我应该把我的连接字符串放在哪里?

5 个答案:

答案 0 :(得分:11)

将其放在<configuration> f.e。

之后的</configSections>
<configuration>
    <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </configSections>
    <connectionStrings>
        <add name="DefaultConnection" connectionString="blablabla" providerName="System.Data.SqlClient" />
    </connectionStrings>    
    <appSettings>
        <add key="webpages:Version" value="3.0.0.0" />
        <add key="webpages:Enabled" value="false" />
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    <system.web>
        <compilation debug="true" targetFramework="4.5.1" />
        <httpRuntime targetFramework="4.5.1" />
    </system.web>
    ...

答案 1 :(得分:2)

<connectionStrings>
      <add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

了解更多herehere

答案 2 :(得分:2)

可以在配置中的任何位置添加连接字符串,这样它应该是配置的子节点。
推荐它应该放在所有标签之后,以便在将来需要更改时保持可见。

    <configuration>
 <connectionStrings>
   <add name="defaultConn" 
        connectionString="Server=SERVER; Database=DbName; User Id=userid; password= password"
        providerName="System.Data.SqlClient" />
 </connectionStrings>
</configuration>

答案 3 :(得分:1)

您可以在配置后立即添加,只需尝试按照配置

<configuration>
 <connectionStrings>
   <add name="SQLDbConnection"
        connectionString="Server=SQlServerName; Database=YouDatabaseName; User Id=userid; password= password"
        providerName="System.Data.SqlClient" />
 </connectionStrings>
</configuration>

答案 4 :(得分:1)

连接字符串位于<connectionStrings>元素内。放置<connectionStrings>的传统地点似乎在<appSettings>之前,但它的确切位置并不重要。