Skip to main content
 首页 » 编程设计

c#之了解子文件夹中的 Web.config 层次结构

2024年08月06日46wuhuacong

在我的 Visual Studio Web 项目中,根目录中有一个 Web.config。

Web.config 文件定义了用于基本网络身份验证的网络 User 和 Password。

<configuration> 
    <appSettings> 
        <add key="User" value="victoria"/> 
        <add key="Pwd" value="i12kissU"/> 
    </appSettings> 
</configuration> 

我的项目使用一个母版页,其中包含几个常用方法。这是我使用上面的应用程序设置的地方:

母版页:

using System.Net; 
using System.Web.Configuration; 
// 
public CredentialCache GetNetworkCredentials(string url) { 
    var item = new CredentialCache(); 
    var username = WebConfigurationManager.AppSettings["User"]; 
    var password = WebConfigurationManager.AppSettings["Pwd"]; 
    item.Add(new Uri(url), "Basic", new NetworkCredential(username, password)); 
    return item; 
} 

在每个子文件夹 中,项目都有访问SQL Server 上不同数据库的例程。因此,每个 SubFolder 都有自己的 Web.config 文件,其中包含用于这些表的唯一数据库连接字符串。

<configuration> 
    <connectionStrings> 
        <add name="SubFolderN" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SubFolderN;User Id=UserN;Password=PwdN" providerName="System.Data.SqlClient" /> 
    </connectionStrings> 
</configuration> 

这让我可以为每个 子文件夹 提取连接字符串。

子文件夹N:

ConnectionString = 
  WebConfigurationManager.ConnectionStrings["SubFolderN"].ConnectionString; 

到目前为止,每个 SubFolder 都成功地从 Master Page 中提取了 User 和 Pwd 值。

“从 Root 继承”是 Web.config 文件的保证属性吗?

到目前为止,结果似乎很有希望。

但是,我想向社区中的某个人确认我所看到的不是浏览器缓存的结果。我需要这种情况始终如一地发生。

带有权威引用的链接会很棒。

请您参考如下方法:

我想我在这里找到了答案:

10 Things ASP.NET Developers Should Know About Web.config Inheritance and Overrides

具体来说,它说的是 ASP.NET Web.config:

The Web.config file for a specific ASP.NET application is located in the root directory of the application and contains settings that apply to the Web application and inherit downward through all of the subdirectories in its branch.