什么是web.config

本文介绍了ASP.NET配置系统的强大功能及其实现方式,包括配置文件的基本用法、高级配置技巧、自定义配置节的方法以及标准配置段等内容。
从文件名就可以看出是做配置用的,比如配置自定义错误页面,debug,等等 
存放连接字符串是最基本的用法, 
高级一点可以配置httpmodule,httphandler... 
再高级一点可以写一个继承自IConfigurationSectionHandler,添加自定义的配置节... 
功能是很强大的 
ASP.NET提供了一个丰富而可行的配置系统,以帮助管理人员轻松快速的建立自己的WEB应用环境。ASP.NET提供的是一个层次配置架构,可以帮助WEB应用、站点、机器分别配置自己的扩展配置数据。ASP.NET的配置系统具有以下优点: 
●ASP.NET允许配置内容可以和静态内容、动态页面和商业对象放置在同一应用的目录结构下。当管理人员需要安装新的ASP.NET应用时,只需要将应用目录拷贝到新的机器上即可。 
●ASP.NET的配置内容以纯文本方式保存,可以以任意标准的文本编辑器、XML解析器和脚本语言解释、修改配置内容。 
●ASP.NET 提供了扩展配置内容的架构,以支持第三方开发者配置自己的内容。 
●ASP.NET配置文件的更修被系统自动监控,无须管理人员手工干预。


4.2.2配置文件的规则 
ASP.NET的配置文件是基于XML格式的纯文本文件,存在于应用的各个目录下,统一命名为“config.web”。它决定了所在目录及其子目录的配置信息,并且子目录下的配置信息覆盖其父目录的配置。 
WINNT\Microsoft.NET\Framework\版本号\下的config.web为整个机器的根配置文件,它定义了整个环境下的缺省配置。 
缺省情况下,浏览器是不能够直接访问目录下的config.web文件。 
在运行状态下,ASP.NET会根据远程URL请求,把访问路径下的各个config.web配置文件叠加,产生一个唯一的配置集合。举例来说,一个对URL: http://localhost/webapp/owndir/test.aspx的访问,ASP.NET会根据以下顺序来决定最终的配置情况: 
1..\Microsoft.NET\Framework\v.1.00\config.web (缺省配置文件) 
2..\webapp\config.web (应用的配置) 
3..\webapp\owndir\config.web (自己的配置) 
4.2.3配置文件的语法规则 
1)标识 
配置内容被置于config.web文件中的标记<configuration>和</configuration>之间。 
格式: 
<configuration> 
配置内容 
… 
</configuration>


2)配置段句柄说明 
ASP.NET的配置文件架构并未指定任何文件格式或者是支持的配置属性。相反的,它提出了“配置段句柄申明”的概念来支持任意的用户定义配置段。 
格式: 
<configsections> 
<add name=欲定义配置段名 type=处理的句柄函数 /> 
</configsections>


3)配置段 
具体定义配置的内容,供应用使用。


以下例子定义了一个“httpmodules”配置段,设置了系统http相关的处理模块


<configuration>


<configsections> 
<add name="httpmodules" type="System.Web.Configuration.HttpModules 
ConfigurationHandler" /> 
</configsections>


<httpmodules> 
<add type="System.Web.SessionState.CookielessSessionModule" /> 
<add type="System.Web.Caching.OutputCacheModule" /> 
<add type="System.Web.SessionState.SessionStateModule" /> 
<add type="System.Web.Security.WindowsAuthenticationModule" /> 
<add type="System.Web.Security.CookieAuthenticationModule" /> 
<add type="System.Web.Security.PassportAuthenticationModule" /> 
<add type="System.Web.Security.CustomAuthenticationModule" /> 
<add type="System.Web.Security.UrlAuthorizationModule" /> 
<add type="System.Web.Security.FileAuthorizationModule" /> 
</httpmodules>


</configuration>


4.2. 4ASP.NET定义的标准配置段 
1)httpmodule 段: 定义了应用的http请求的处理模块以及诸如安全、日志之类的应用方式 
2)httphandlers 段: 负责映射URLs到IhttpHandler类 
3)sessionstat 段: 负责配置http模块的会话状态 
4)globalization 段: 配置应用的公用设置 
5)compilation 段: 配置ASP.NET的编译环境 
6)trace    段: 配置ASP.NET的跟踪服务 
7)security 段: ASP.NET的安全配置 
8)iisprocessmodel 段: 在IIS上配置ASP.NET的处理模式 
9)browercaps 段: 配置浏览器的兼容部件 
4.2. 5一个配置读出的例子 
1)config.web配置文件


<!--config.web 请放入FormCfg.aspx所在目录--> 
<configuration> 
<!--申明一个test配置段--> 
<configsections> 
<add name="test" type="System.Web.Configuration.DictionarySectionHandler" /> 
</configsections>


<test> 
<!--配置一个键key,其内容为just a configure test-->


<add key="key" value="just a configure test" /> 
</test> 


</configuration>


2)读出其内容


<!--文件名:Application/FormCfg.aspx--> 
<html> 
<head> 
<script language="VB" runat=server> 
sub page_load(s as object ,e as eventargs) 
'取出test配置段的key键的值 
Dim CfgSection As Hashtable = Context.GetConfig("test") 
Dim Msg As String = CStr(CfgSection("key"))


lblMsg.text=Msg 
end sub 
</script> 
<title> 
配置信息的读取 
</title> 
</head>


<body> 
<center> 
config.web中"test"配置段中key的内容为: 
<asp:label id=lblmsg runat=server /> 
</center> 
</body>


</html>


3)运行结果


4.2. 6Config.web配置实例 
<configuration> 
<!--定义用户应用的公用设置,如SQL的sql连接串等等--> 
<appsettings> 
</appsettings>


<!--设置浏览器的兼容性部件--> 
<browsercaps> 
</browsercaps>


<!--编译环境设置,非调试模式--> 
<compilation debugmode="false"> 
<!--缺省编译语言为vb,以后可以不再在Page中定义脚本语言--> 
<compilers defaultlanguage="vb"> 
<!--以MSVSA.dll编译.vb为后缀的VB文件--> 
<compiler language="VB" extension=".vb" type="MSVSA.dll#Microsoft.VB.Compiler"/> 
</compilers>


<assemblies> 
<!--加入对System.Data的引用--> 
<add assembly="System.Data" /> 
<!--去掉对System.Data的引用--> 
<remove assembly="System.IO" /> 
<!--去掉config.web中包含或继承来的引用--> 
<clear /> 
</assemblies>


</compilation>


<!--设置应用全局环境--> 
<!--文件、请求、返回以gb2312编码,以保证浏览器正确显示中文--> 
<globalization fileencoding="gb2312" requestencoding="gb2312" 
responseencoding="gb2312"/>


<!--定义用户出错的处理--> 
<!--出错缺省显示defaultredirect指定的页面,mode为on时,遵循customerrors配置段--> 
<!--mode为off时,忽略用户出错,mode为remoteonly时,本地才显示真正的出错原因--> 
<customerrors defaultredirect="AnErrorHasOccured.aspx?ErrNum=-1" mode="remote"> 
<!--当出错码为500时,显示redirect指定的页面--> 
<error statuscode="500" redirect="AnErrorHasOccured.aspx?ErrNum=500"/> 
</customerrors>


<!--指定目录webapp的访问权限--> 
<location path="webapp” > 
<!--非授权用户不能进入webapp目录--> 
<security> 
<authorization> 
<deny users="?" /> 
</authorization> 
</security> 
</location>


<!--定义安全属性--> 
<security> 
<authorization> 
<!--角色为Adminstrators和所有的用户访问其指定的资源--> 
<allow roles="Adminstrators"/> 
<allow users="*" /> 
</authorization> 
</security>


</configuration>

<think>我们被问到“Web.config是什么”,这是一个关于ASP.NET配置系统的问题。需要详细解释Web.config文件的作用、结构和使用方法,并给出相关代码示例(如果适用)。最后按照要求提出四个相关问题。回答结构:1.解释Web.config是什么2.说明其主要功能和特点3.展示一个典型的Web.config文件结构(代码示例)4.解释其中常见的配置节5.提出相关问题</think>### Web.config 详解 Web.config 是 ASP.NET 应用程序的核心配置文件,它使用 XML 格式定义应用程序的各种设置和行为。这个文件位于 ASP.NET 应用程序的根目录中,控制着应用程序的几乎所有方面。 #### Web.config 的主要功能 1. **应用程序设置**: - 存储数据库连接字符串 - 配置应用程序参数 - 定义自定义设置 2. **运行时行为**: - 配置会话状态(Session State) - 设置编译选项 - 定义错误处理策略 3. **安全配置**: - 身份验证(Authentication) - 授权(Authorization) - 角色管理(Role Management) 4. **性能优化**: - 缓存配置 - 输出压缩 - HTTP 模块配置 #### 典型 Web.config 结构示例 ```xml <?xml version="1.0" encoding="utf-8"?> <configuration> <!-- 应用程序设置 --> <appSettings> <add key="ApplicationName" value="MyWebApp" /> <add key="MaxRecords" value="100" /> </appSettings> <!-- 数据库连接字符串 --> <connectionStrings> <add name="DefaultConnection" connectionString="Server=.;Database=MyDB;Integrated Security=True;" providerName="System.Data.SqlClient" /> </connectionStrings> <!-- 系统设置 --> <system.web> <!-- 编译设置 --> <compilation debug="true" targetFramework="4.8" /> <!-- 身份验证 --> <authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="30" /> </authentication> <!-- 授权规则 --> <authorization> <deny users="?" /> <!-- 拒绝匿名用户 --> </authorization> <!-- 会话状态 --> <sessionState mode="InProc" timeout="20" /> <!-- 自定义错误 --> <customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx"> <error statusCode="404" redirect="~/NotFound.aspx" /> </customErrors> <!-- HTTP 模块 --> <httpModules> <add name="ErrorLog" type="MyApp.Modules.ErrorLogger" /> </httpModules> </system.web> <!-- 特定于 IIS 的设置 --> <system.webServer> <modules> <remove name="FormsAuthentication" /> <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" /> </modules> <!-- 处理程序映射 --> <handlers> <add name="MyHandler" path="*.custom" verb="*" type="MyApp.CustomHandler" /> </handlers> </system.webServer> <!-- 位置特定配置 --> <location path="Admin"> <system.web> <authorization> <allow roles="Administrators" /> <deny users="*" /> </authorization> </system.web> </location> </configuration> ``` #### 关键配置部分详解 1. **`<connectionStrings>`** 存储数据库连接字符串,可通过代码访问: ```csharp string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; ``` 2. **`<appSettings>`** 存储自定义键值对配置: ```csharp string appName = ConfigurationManager.AppSettings["ApplicationName"]; ``` 3. **身份验证配置** ```xml <authentication mode="Windows|Forms|Passport|None"> <forms loginUrl="~/Login.aspx" timeout="30" /> </authentication> ``` 4. **授权规则** ```xml <authorization> <allow users="?"/> <!-- 允许匿名用户 --> <allow roles="Admins"/> <!-- 允许管理员角色 --> <deny users="*"/> <!-- 拒绝所有用户 --> </authorization> ``` 5. **自定义错误处理** ```xml <customErrors mode="On|Off|RemoteOnly" defaultRedirect="~/Error.aspx"> <error statusCode="404" redirect="~/NotFound.aspx"/> </customErrors> ``` #### 分层配置继承 Web.config 支持分层配置结构: ``` 服务器级别 (Machine.config) | 站点根目录 (Web.config) | 子目录 (Web.config) ``` - 子目录中的 Web.config 继承父目录设置 - 子目录设置可以覆盖父目录设置 - `Machine.config` 包含所有 ASP.NET 应用程序的默认设置 #### 在代码中访问配置 ```csharp using System.Configuration; using System.Web.Configuration; public class ConfigHelper { // 获取连接字符串 public static string GetConnectionString(string name) { return WebConfigurationManager.ConnectionStrings[name].ConnectionString; } // 获取应用设置 public static string GetAppSetting(string key) { return WebConfigurationManager.AppSettings[key]; } // 修改配置(运行时) public static void UpdateAppSetting(string key, string value) { Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); config.AppSettings.Settings[key].Value = value; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } } ``` #### Web.config 最佳实践 1. **安全注意事项**: - 不要在配置文件中存储明文密码 - 使用 `aspnet_regiis` 工具加密敏感部分: ``` aspnet_regiis -pe "connectionStrings" -app "/MyApp" ``` - 限制配置文件访问权限 2. **性能优化**: - 生产环境设置 `debug="false"` - 合理配置缓存策略 - 使用 `<httpRuntime>` 优化请求处理 3. **维护技巧**: - 使用配置转换(Web.Debug.config, Web.Release.config) - 合理组织配置节 - 为不同环境创建单独的配置文件 4. **调试帮助**: ```xml <system.web> <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="true"/> </system.web> ``` 访问方式:`http://yoursite/trace.axd` #### Web.config 与 ASP.NET Core 的 appsettings.json 在 ASP.NET Core 中,Web.config 被替代为: - `appsettings.json` - 应用配置 - `launchSettings.json` - 启动配置 - `Program.cs` - 代码配置 但传统 ASP.NET 应用程序仍依赖 Web.config
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值