ASP.NET - Web.config

<?xml version="1.0"?>

<!--注意: 除了手动编辑此文件以外,您还可以使用 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。

设置和注释的完整列表在 machine.config.comments 中,该文件通常位于 "Windows"Microsoft.Net"Framework"v2.x"Config 中。-->

 <!--Webconfig文件是一个xml文件,configuration是xml文件的根节点,由于xml文件的根节点只能有一个,所以Webconfig的所有配置都是在这个节点内进行的。-->

<configuration>

  <!--指定配置节和命名空间声明。clear:移除对继承的节和节组的所有引用,只允许由当前 section 和 sectionGroup 元素添加的节和节组。remove:移除对继承的节和节组的引用。

 section:定义配置节处理程序与配置元素之间的关联。sectionGroup:定义配置节处理程序与配置节之间的关联。-->

 <configSections>

    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

        <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

      </sectionGroup>

    </sectionGroup>

    <section name="rewriter" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />

 </configSections>

 

 <!--appSettings是应用程序设置,可以定义应用程序的全局常量设置等信息-->

     <appSettings>

 <add key="1" value="1" />

 <add key="gao" value="weipeng" />

 </appSettings>

 

 <!--连接字符串设置-->

 <connectionStrings>

    <add name="ConnString" connectionString="Data Source=GAO;Initial Catalog=HBWXDate;User ID=sa;password=sa"></add>

    <add name="111" connectionString="11111" />

 </connectionStrings>

 

 <!--指定应用子配置设置的资源,并锁定配置设置,以防止它们被子配置文件重写。page指定应用包含的配置设置的资源.allowOverride是否允许配置文件的重写,提高配置文件的安全性-->

 <location path="Default.aspx" allowOverride="false">

    <!--控制asp.net运行时的行为-->

<system.web>

    <!--identity控制web应用程序的身份验证标识.-->

    <identity impersonate="false" />

   

    <!--标识特定于页的配置设置(如是否启用会话状态、视图状态,是否检测用户的输入等)。<pages>可以在计算机、站点、应用程序和子目录级别声明.

    这里的几个属性的意思是默认主页为Index,主题是Default,不检测用户在浏览器输入的内容中是否存在潜在的危险数据(注:该项默认是检测,如果你使用了不检测,一要对用户的输入进行编码或验证),在从客户端回发页时将检查加密的视图状态,以验证视图状态是否已在客户端被篡改。(注:该项默认是不验证)禁用ViewState-->

    <pages masterPageFile="Index" theme="Default" buffer="true" enableViewStateMac="true" validateRequest="false" enableViewState="false">

      <!--controls 元素定义标记前缀所在的 register 指令和命名空间的集合-->

      <controls></controls>

      <!--将在程序集预编译期间使用的导入指令的集合-->

      <namespaces></namespaces>

    </pages>

   

    <!--默认错误页设置,mode:具有On,Off,RemoteOnly 3种状态。On表示始终显示自定义的信息; Off表示始终显示详细的asp.net错误信息; RemoteOnly表示只对不在本地Web服务器上运行的用户显示自定义信息.defaultRedirect:用于出现错误时重定向的URL地址-->

    <customErrors defaultRedirect="Err.html" mode="RemoteOnly">

      <!--特殊代码编号的错误从定向文件-->

      <error statusCode="403" redirect="NoAccess.htm" />

      <error statusCode="404" redirect="FileNotFound.htm" />

    </customErrors>

   

    <!--配置调试和跟踪:下面配置的意思是启动调试(默认),捕获跟踪信息,要缓存的跟踪请求个数(15),跟踪结果的排列顺序-->

    <trace enabled="true" localOnly="false" pageOutput="true" requestLimit="15" traceMode="SortByCategory"/>

   

    <!-- 设置 compilation debug="true" 将调试符号插入已编译的页面中。但由于这会影响性能,因此只在开发过程中将此值设置为 true。设置默认的开发语言C#。batch是否支持批处理-->

    <compilation debug="true" defaultLanguage="c#" batch="false">

      <assemblies>

        <!--加的程序集引用,每添加一个程序集,就表示你的应用程序已经依赖了一个程序集,你就可以在你的应用程序中使用了-->

        <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

        <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

        <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

        <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

        <add assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

        <add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

        <add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

        <add assembly="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

        <add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

        <add assembly="System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

        <add assembly="System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>

      </assemblies>

      <!--定义用于编译自定义资源文件的生成提供程序的集合。-->

      <buildProviders>

        <!---->

        <add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/>

        <add extension=".ascx" type="System.Web.Compilation.UserControlBuildProvider"/>

        <add extension=".master" type="System.Web.Compilation.MasterPageBuildProvider"/>

        <add extension=".asmx" type="System.Web.Compilation.WebServiceBuildProvider"/>

        <add extension=".ashx" type="System.Web.Compilation.WebHandlerBuildProvider"/>

        <add extension=".soap" type="System.Web.Compilation.WebServiceBuildProvider"/>

        <add extension=".resx" type="System.Web.Compilation.ResXBuildProvider"/>

        <add extension=".resources" type="System.Web.Compilation.ResourcesBuildProvider"/>

        <add extension=".wsdl" type="System.Web.Compilation.WsdlBuildProvider"/>

        <add extension=".xsd" type="System.Web.Compilation.XsdBuildProvider"/>

        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>

      </buildProviders>

    </compilation>

   

      <!--通过 <authentication> 节可以配置 ASP.NET 使用的 安全身份验证模式,以标识传入的用户。Windows: 使用IIS验证方式,Forms: 使用基于窗体的验证方式,Passport: 采用Passport cookie验证模式,None: 不采用任何验证方式-->

    <authentication mode="Forms">

      <!--Name: 指定完成身份验证的Http cookie的名称.LoginUrl: 如果未通过验证或超时后重定向的页面URL,一般为登录页面,让用户重新登录。Protection: 指定 cookie数据的保护方式. 

      可设置为:All表示加密数据,并进行有效性验证两种方式,None表示不保护Cookie,Encryption表示对Cookie内容进行加密,validation表示对Cookie内容进行有效性验证,TimeOut: 指定Cookie的失效时间. 超时后要重新登录。-->

      <forms name=".ASPXUSERDEMO" loginUrl="Login.aspx" protection="All" timeout="30"/>

    </authentication>

    <!--控制对 URL 资源的客户端访问(如允许匿名用户访问)。此元素可以在任何级别(计算机、站点、应用程序、子目录或页)上声明。必需与<authentication> 节配合使用。此处的意思是对匿名用户不进行身份验证。拒绝用户weipeng-->

    <authorization>

      <allow users="*"/>

      <deny users="weipeng"/>

      <allow users="aa" roles="aa" />

    </authorization>

    <!--站点全球化设置,requestEncoding: 它用来检查每一个发来请求的编码.responseEncoding: 用于检查发回的响应内容编码.fileEncoding:用于检查aspx,asax等文件解析的默认编码,默认的编码是utf-8-->

    <globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312" />

    <!--会话状态设置。mode: 分为off,Inproc,StateServer,SqlServer几种状态 mode = InProc 存储在进程中特点:具有最佳的性能,速度最快,但不能跨多台服务器存储共享.mode = "StateServer" 存储在状态服务器中特点:当需要跨服务器维护用户会话信息时,使用此方法。但是信息存储在状态服务器上,一旦状态服务器出现故障,信息将丢失. mode="SqlServer" 存储在sql server中特点:工作负载会变大,但信息不会丢失

    stateConnectionString :指定asp.net应用程序存储远程会话状态的服务器名,默认为本机。sqlConnectionString:当用会话状态数据库时,在这里设置连接字符串。Cookieless:设置为flase时,表示使用cookie会话状态来标识客户.timeout表示会话超时时间。-->

    <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"></sessionState>

    <!--为 ASP.NET 应用程序配置页的视图状态设置。设置要存储在页历史记录中的项数。-->

    <sessionPageState historySize="9"/>   

    <!--配置asp.net http运行库的设置。可以在计算机,站点,应用程序和子目录级别声明

    允许最多的请求个数100,最长允许执行请求时间为80秒,控制用户上传文件的大小,默认是4M。useFullyQualifiedRedirectUrl客户端重定向不需要被自动转换为完全限定格式。-->

    <httpRuntime appRequestQueueLimit="100" executionTimeout="80" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/>

    <!--httpModules在一个应用程序内配置 HTTP 模块。-->

    <httpModules>

      <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" />

      <add name="Session" type="System.Web.SessionState.SessionStateModule" />

      <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" />

      <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />

      <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" />

      <add name="RoleManager" type="System.Web.Security.RoleManagerModule" />

      <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" />

      <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" />

      <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" />

      <!--自定义的URL重写,type基本上就是dll名-->

      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />

      <add name="Profile" type="System.Web.Profile.ProfileModule" />

    </httpModules> 

    <!--httpHandlers用于根据用户请求的URL和HTTP谓词将用户的请求交给相应的处理程序。可以在配置级别的任何层次配置此节点,也就是说可以针对某个特定目录下指定的特殊文件进行特殊处理。

    add:指定映射到处理程序的谓词/路径。clear:移除当前已配置或已继承的所有处理程序映射。remove:移除映射到处理程序的谓词/路径。remove 指令必须与前一个 add 指令的谓词/路径组合完全匹配。该指令不支持通配符。-->

    <httpHandlers>

      <remove verb="*" path="*.asmx"/>

      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>

    </httpHandlers>

    <!--为 Web 应用程序使用的 Cookie 配置属性。domain:设置 Cookie 域名。httpOnlyCookies:在 Internet Explorer 6 SP1 中启用 HttpOnlyCookies Cookie 的输出。默认值为 false。requireSSL:获取一个指示是否需要安全套接字层 (SSL) 通信的值.-->

    <httpCookies httpOnlyCookies="false" requireSSL="false"/> 

    <!--控制 ASP.NET Web 服务及其客户端的行为。protocols:指定传输协议,ASP.NET 可使用这些传输协议来解密 HTTP-->

    <webServices>

      <protocols>

        <add/>

      </protocols>

    </webServices>

    <!--为 Web 应用程序配置缓存设置。cache:定义全局应用程序缓存设置。outputCache :指定应用程序范围的输出缓存设置。outputCacheSettings:指定可以应用于应用程序中页的输出缓存设置。sqlCacheDependency:为 ASP.NET 应用程序配置 SQL 缓存依赖项。-->

    <caching>

      <cache disableMemoryCollection = "false" disableExpiration = "false" privateBytesLimit = "0" percentagePhysicalMemoryUsedLimit = "90" privateBytesPollTime = "00:02:00"/>

      <!--设计需要以这种方式缓存的页时,您需要向该页添加以下指令:<%@ OutputCache CacheProfile="ServerOnly" %>-->

      <outputCacheSettings>

        <outputCacheProfiles>

          <add name="ServerOnly" duration="60" varyByCustom="browser" location="Server" />

        </outputCacheProfiles>

      </outputCacheSettings>

    </caching>

     </system.web>

 </location>

 <!--网络设置,authenticationModules:指定用于对 Internet 请求进行身份验证的模块。connectionManagement:指定与 Internet 宿主的连接的最大数目。defaultProxy:配置超文本传输协议 (HTTP) 代理服务器。

 mailSettings:配置简单邮件传输协议 (SMTP) 邮件发送选项。requestCaching:控制网络请求的缓存机制。settings:配置 System.Net 的基本网络选项。-->

 <system.net>

 <!--配置SMTP电子邮件设置-->

 <mailSettings>

   <smtp from="weipeng">

    <network host="Gao" password="" userName="" />

   </smtp>

 </mailSettings>

   <!--禁用所有缓存-->

   <requestCaching disableAllCaching="true"></requestCaching>

   <!--指定代理地址,并对本地访问和 contoso.com 跳过代理。-->

   <defaultProxy>

     <proxy usesystemdefault="True" proxyaddress="http://192.168.1.10:3128" bypassonlocal="True"/>

     <bypasslist>

       <add address="[a-z]+".contoso".com" />

     </bypasslist>

   </defaultProxy>

 </system.net>

 <!--该节替换在 httpHandlers 和 httpModules 节中添加的与 AJAX 相关的 HTTP 处理程序和模块。该节使 IIS 7.0 在集成模式下运行时可使用这些处理程序和模块。在iis7.0 下运行 ASP.NET AJAX 需要 system.webServer

 节。对早期版本的 IIS 来说则不需要此节。 -->

 <system.webServer>

    <validation validateIntegratedModeConfiguration="false"/>

    <modules>

      <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    </modules>

    <handlers>

      <remove name="WebServiceHandlerFactory-Integrated"/>

      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

    </handlers>

 </system.webServer>

 

 <!--ASP.NET AJAX 中配置 ASP.NET 服务-->

 <system.web.extensions>

    <!--配置 JSON 序列化-->

    <scripting>

      <webServices>

        <jsonSerialization maxJsonLength="5000"/>

      </webServices>

    </scripting>

 </system.web.extensions>

 <!--对WCF的相关配置-->

 <system.serviceModel>

    <services>

      <service name="WCFStudent.WCFStudentText" behaviorConfiguration="ServiceBehavior">

        <!-- Service Endpoints -->

        <endpoint address="" binding="wsHttpBinding" contract="WCFStudent.IStuServiceContract">

          <!-- 部署时,应删除或替换下列标识元素,以反映在其下运行部署服务的标识。删除之后,WCF 将自动推导相应标识。-->

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehavior">

          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false 并删除上面的元数据终结点 -->

          <serviceMetadata httpGetEnabled="true"/>

          <!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息-->

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

    </behaviors>

 </system.serviceModel>

 

 <!--URL重定向-->

 <rewriter>

    <rewrite url="~/user/u(.+).aspx" to="~/user/index.aspx?r=$1" />

    <rewrite url="~/ask/q(.+).aspx" to="~/home/ask/content.aspx?id=$1" />

    <rewrite url="~/blog/b(.+).aspx" to="~/home/blog/article.aspx?r=$1" />

    <rewrite url="~/news/n(.+).aspx" to="~/home/news/content.aspx?nid=$1" />

    <rewrite url="~/default.aspx" to="~/home/ram/net.aspx" />

 </rewriter>

</configuration>

 

 

 

.net 提供的是针对当前机器的配置。---名称:machine.config

运行机制:asp.net网站IIS启动的时候会加载配置文件中的配置信息,然后缓存这些信息,这样就不必每次去读取配置信息。在运行过程中asp.net应用程序会监视配置文件的变化情况,一旦编辑了这些配置信息,就会重新读取这些配置信息并缓存。

配置文件节点:
  必须明白: web.config文件是一个XML文件
  所隶属根节点的名称:

 

复制代码代码如下:

  <configuration>
         子节点:<configSections></configSections>
             <appSettings> </appSettings>
            <connectionStrings></connectionStrings>
            <system.web></system.web>
       特殊: <system.webServer></system.webServer>-----用于指定适用于 Web 应用程序的 IIS 7.0 设置,只适用于 IIS 7.0 集成模式 不适用于经典模式,如果应用程序正在经典模式下运行,则会忽略 Web.config 文件的
  <configuration> 

 

  节点分析:
1.<connectionStrings>节点

  主要用于配置数据库连接,可以在<connectionStrings>节点中增加任意个节点来保存数据库连接字符串然后通过代码的方式动态获取节点的值来实例化数据库连接对象。
例如:

 

复制代码代码如下:

    <connectionStrings>
        <!--SQL Server数据库配置-->   <add name="你所要取的名字(任意的)"  connectionString=" Date Source=数据库登陆名 ; Initial Catalog=数据库名称; User ID=登录人    Password=登录人密码 "/>是可以配置多个数据库的连接的
        <add name="AspNetStudyConnectionString1" connectionString="Data Source=(local);Initial Catalog=AspNetStudy;User ID=sa;Password=sa"/>
        <add name="ConnectionString" connectionString="Data Source=10.0.0.52;Initial Catalog=NEW_HOSPITAL_DEV;User ID=hospital;pwd=hospital;"/>
    </connectionStrings>

 

在代码中药读取数据库连接对象的做法:

 

复制代码代码如下:

    //读取web.config节点配置
    string connectionString = ConfigurationManager.ConnectionStrings["AspNetStudyConnectionString1"].ConnectionString;
    //实例化SqlConnection对象
    SqlConnection connection = new SqlConnection(connectionString);

 

从中可以看出好处:一旦开发时所用的数据库和部署时的数据库不一致,仅仅需要用记事本之类的文本编辑工具编辑connectionString属性的值就行了

2.<appSettings>节点

   作用:存储asp.net应用程序的一些配置信息,比如上传文件的保存路径等
例如可以配置图片类型:

 

复制代码代码如下:

    <appSettings>
        <add key="ImageType" value=".jpg;.bmp;.gif;.png;.jpeg"/>----<!--允许上传的图片格式类型-->
        <add key="FileType" value=".jpg;.bmp;.gif;.png;.jpeg;.pdf;.zip;.rar;.xls;.doc"/><!--允许上传的文件类型-->
    </appSettings>

 

读取</appSettings>节点中的值:

string  FileType= ConfigurationManage.AppSettings["FileType"]; ----其实就是键值对的形式 取值的

3.<system.web> 节点:

所属子节点:

3.1.<compilation>节点
            作用:节点配置 ASP.NET 使用的所有编译设置。默认的debug属性为“true”,即允许调试,在这种情况下会影响网站的性能所以在程序编译完成交付使用之后应将其设为“false”
例如:

 

复制代码代码如下:

            <compilation targetFramework="4.0" debug="true">
            <buildProviders>
                <add extension=".html" type="System.Web.Compilation.PageBuildProvider"/>
            </buildProviders>
            </compilation>

 

3.2.<authentication>节点
        作用:控制用户对网站、目录或者单独页的访问

设置asp.net身份验证模式,有四种身份验证模式,它们的值分别如下:
Mode 说明
Windows 使用Windows身份验证,适用于域用户或者局域网用户。
Forms 使用表单验证,依靠网站开发人员进行身份验证。
Passport 使用微软提供的身份验证服务进行身份验证。
None 不进行任何身份验证。
 例如:            <!--请求模式-->
        <authentication mode="Forms"/>

 3.2.<customErrors>节点

 <customErrors>节点用于定义 一些自定义错误信息的信息。此节点有Mode和defaultRedirect两个属性,其中defaultRedirect属性是一个可选属性,表示应 用程序发生错误时重定向到的默认URL,如果没有指定该属性则显示一般性错误。Mode属性是一个必选属性,它有三个可能值,它们所代表的意义分别如下:
Mode 说明
On     表示在本地和远程用户都会看到自定义错误信息。
Off    禁用自定义错误信息,本地和远程用户都会看到详细的错误信息。
RemoteOnly 表示本地用户将看到详细错误信息,而远程用户将会看到自定义错误信息。
这 里有必要说明一下本地用户和远程用户的概念。当我们访问asp.net应用程时所使用的机器和发布asp.net应用程序所使用的机器为同一台机器时成为 本地用户,反之则称之为远程用户。在开发调试阶段为了便于查找错误Mode属性建议设置为Off,而在部署阶段应将Mode属性设置为On或者 RemoteOnly,以避免这些详细的错误信息暴露了程序代码细节从而引来黑客的入侵。

例子:

 

复制代码代码如下:

<!--错误跳转 mode="RemoteOnly"-->
        <customErrors mode="Off" defaultRedirect="/Error.aspx">
            <error statusCode="404" redirect="/404.aspx"/>
            <error statusCode="500" redirect="/500.aspx"/>
        </customErrors>

 

3.3<error>子节点

            在<customErrors>节点下还包含 有<error>子节点,这个节点主要是根据服务器的HTTP错误状态代码而重定向到我们自定义的错误页面,注意要 使<error>子节点            下的配置生效,必须将<customErrors>节点节点的Mode属性设置为“On”。下面是一个例 子:

 

复制代码代码如下:

    <customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
         <error statusCode="403" redirect="403.htm" />--如果用户没有权限访问请求的页面则会跳转到403.htm页面
         <error statusCode="404" redirect="404.htm" />--如果用户访问的页面不存在就会跳转到404.htm页面
    </customErrors>

 

    403.htm和404.htm页面都是我们自己添加的页面

3.4<httpHandlers>节点 

                 作用:用于根据用户请求的URL和HTTP谓词将用户的请求交给相应的处理程序,处理的结果就是用户不能查看或者下载相关的文件

         如果我们某个文件夹下的文件或 者某个类型的文件不允许用户下载,可以在</httpHandlers>节点中增加相应的子节点。

例子:我们的asp.net应用程序中建立一个IPData目录,在IPData目录中创建一个IPData.txt文件,在Web.config中添加以下配置

 

复制代码代码如下:

    <httpHandlers>
          <add path="IPData/*.txt" verb="*" type="System.Web.HttpForbiddenHandler"/>---代码的作用是禁止访问IPData目录下的任何txt文件
     <add path="*.mdf" verb="*" type="System.Web.HttpForbiddenHandler" validate="true"/>
            <add path="*.ldf" verb="*" type="System.Web.HttpForbiddenHandler" validate="true"/>---针对*.mdf、*.ldf文件,Get或者Post请求都会交给 System.Web.HttpForbiddenHandler来处理,用户不能查看或者下载相关的文件
    </httpHandlers>

 

 3.5.<httpRuntime>节点 

    用于对 ASP.NET HTTP 运行库设置。该节可以在计算机、站点、应用程序和子目录级别声明。
    例如下面的配置控制用户最大能上传的文件为40M(40*1024K),最大超时时间为60秒,最大并发请求为100个。

    <httpRuntime maxRequestLength="40960" executionTimeout="60" appRequestQueueLimit="100"/>

 3. 6.<pages>节点

用于表示对特定页设置,主要有三个属性

    属性名 说明
    buffer 是否启用了 HTTP 响应缓冲。
    enableViewStateMac 是否应该对页的视图状态运行计算机身份验证检查 (MAC),以放置用户篡改,默认为false,如果设置为true将会引起性能的降低。
    validateRequest 是 否验证用户输入中有跨站点脚本攻击和SQL注入式漏洞攻击,默认为true,如果出现匹配情况就会发 HttpRequestValidationException 异常。对于包含有在线    文本编辑器页面一般自行验证用户输入而将此属性设为false。
    下面就是一个配置节点的例子:

     <pages buffer="true" enableViewStateMac="true" validateRequest="false"/>

3.7<sessionState>节点
<sessionState>节点用于配置当前asp.net应用程序的会话状态配置。以下就是一个常见配置:

    <sessionState cookieless="false" mode="InProc" timeout="30" />

上面的节点配置是设置在asp.net应用程序中启用Cookie,并且指定会话状态模式为在进程中保存会话状态,同时还指定了会话超时为30分钟。
<sessionState>节点的Mode属性可以是以下几种值之一:
属性值 说明
Custom 使用自定义数据来存储会话状态数据。
InProc 默认值。由asp.net辅助进程来存储会话状态数据。
Off 禁用会话状态。
SQLServer 使用进程外SQL Server数据库保存会话状态数据。
StateServer 使用进程外 ASP.NET 状态服务存储状态信息。
一般默认情况下使用InProc模式来存储会话状态数据,这种模式的好处是存取速度快,缺点是比较占用内存,所以不宜在这种模式下存储大型的用户会话数据。

4<system.webServer>

----------------------
<defaultDocument>
作用:当请求 URL 未包含 Web 应用程序的特定文件时,IIS 7.0 将提供一个默认文件。
在 system.webServer 元素内,创建一个 defaultDocument 元素。

在 defaultDocument 元素内,创建一个 files 元素。

在 files 元素内创建一个 add 元素,并在 value 属性内指定默认文件的路径和名称。

<configuration>
  <system.webServer>
    <defaultDocument>      
        <files>        
            <add value="Products.aspx" />      
        </files>    
    </defaultDocument>
    -----配置默认文件,为提供 Products.aspx 文件作为默认文件
  </system.webServer>
</configuration>    

 

 

转载自 https://www.cnblogs.com/gaoweipeng/archive/2009/05/17/1458762.html

 

 

 

 

 

 

很多时候我们会有这样的情况,开发环境和测试环境中的配置文件是不一样的,最明显的就是数据库连接串,这样,每次我们发布一个测试版本,都要手动去修改一下配置文件,是不是很麻烦的说。其实利用web.config中的configSource属性,可以很方便的为我们指定外部配置为该节点的内容。这样我们在web.config中只需要指定该配置的configSource的路径就行,而我们再发布的时候,就不需要再修改web.config文件了。

例如,将connectionStrings指定为外部文件:db.config

原配置:

复制代码
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication1-20140304225906;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20140304225906.mdf"
      providerName="System.Data.SqlClient" />
    <add name="ReportServerTempDBConnectionString" connectionString="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
复制代码

指定外部文件:

  <connectionStrings configSource="db.config"/>

外部文件db.config:

复制代码
 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-WebApplication1-20140304225906;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-WebApplication1-20140304225906.mdf"
      providerName="System.Data.SqlClient" />
    <add name="ReportServerTempDBConnectionString" connectionString="Data Source=.;Initial Catalog=ReportServerTempDB;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
复制代码

说几个注意点:

1.如果指定了configSource,就以外部文件为准,web.config中connectionStrings下面的节点配置就无效了,即使web.config中connectionStrings下面的连接串节点没有删除掉也是无效的。

2.外部文件的根节点必须与web.config中指定的节点相同(其实就是将该节点的配置移到外部文件中)

3.一个节点只能指定一个外部配置文件,不能将多个节点的外部文件指定为同一个,如不能将connectionStrings与appSettings的configSource指定为同一个文件。

4.外部文件与web.config处在同一目录。

 

 

 

一个大项目里可能会有非常多个配置参数,有.Net自己支持的配置(比如WCF,AppSettings),还有一部分是自定义的配置(比如继承自ConfigurationSection和ConfigurationElement的配置类),当然还有一部分是第三方类库的配置(其实也是自定义的配置,比如AOP框架Unity),当这些配置变得越来越多的时候,维护起来变得相当困难,特别是config文件内容相当的长和文件的容量过大,过大的文件在Config初始化读取文件时会带来性能影响,这个时候使用configSouce指定外部的文件,拆分成多个不同的文件存储配置,增强可读性和可维护性,降低出错的风险。

MSDN里提到了3点好处:

Using include files can result in a more logical and modular structure for configuration files. (模块化管理文件)

File-access security and permissions can be used to restrict access to sections of configuration settings. (可控制不同配置文件的访问权限)

Settings in an include file that are not used during application initialization can be modified and reloaded without requiring an application restart. (修改不在应用程序初始化时候使用的参数,不需要重启应用)

很多文章里都也已经说了关于ConfigSouce的用法,根据MSDN说明,ConfigSouce只能用于ConfigurationSection对应的节点,比如

<appSettings configSource="Config\\AppSettings\\appSettings.config">
</appSettings>

在appSettings.config里

<appSettings>
  <add key="IOS" value=""/>
  <add key="Android" value=""/>
</appSettings>

这里appSettings是定义在machine.config里configSection,这样.Net会自动找到对应文件。

对于appSettings,在Web.config里IDE会给你智能提示,告诉你它支持configSouce属性,但是有些不会,比如配置WCF服务的system.serviceModel/services节点,这种节点也是支持的,因为从machine.config里会看到,services也是一个ConfigurationSection

Capture

所以如下配置是正确的:

<services configSource="Config\\ServiceModel\\Services.config">
 </services>

对于自定义的配置,或者第三方类库配置,因为都是继承了ConfigurationSection

Capture

所以如下配置也是正确的:

自定义的邮件相关配置

<VRentEmail configSource="Config\\VRentEmail\\VRentEmail.config">
</VRentEmail>

Unity的配置

<unity configSource="Config\\Unity\\Unity.config">
 </unity>

使用了configSource后有一个明显的缺点就是,智能感知没有了

 
 
 
 
 
 
 

先插句题外话,下版本的ASP.NET貌似把web.config撸掉了,都变成json了。所以本文讨论的内容可能以后用不到了,但是一些设计思想还是可以用的~
直接进入正题,在ASP.NET网站里(也包括其他有web.config, app.config)的.NET工程里,读AppSettings的值是个很常见的场景。比如:

<add key="EnableAzureWebTrace" value="true"/>
ConfigurationManager.AppSettings["EnableAzureWebTrace"];

这个[]索引器返回的是string类型。所以下一步我们通常需要类型转换才能在代码里拿来用。比如这个例子里,我们就要转换成bool。其他时候,可能要转换为int等类型。

string enableAzureWebTraceConfig = ConfigurationManager.AppSettings["EnableAzureWebTrace"];
bool enableAzureWebTrace = bool.Parse(enableAzureWebTraceConfig);
if(enableAzureWebTrace)
{
// do some logic
}

但问题是,config文件的值对于我们代码来说是不稳定因素,不可控的,这里拿回来的string未必能正确转换格式。所以通常我们会用TryParse方法来防爆:

string enableAzureWebTraceConfig = ConfigurationManager.AppSettings["EnableAzureWebTrace"];
bool enableAzureWebTrace = false;
if (bool.TryParse(enableAzureWebTraceConfig, out enableAzureWebTrace) && enableAzureWebTrace)
{
// do some logic
}
else
{
throw new ConfigurationException("EnableAzureWebTrace value must be true of false.");
}

当然,不要忘了一点。读出来的string有可能首先就是空的。所以又得加上对string的判断,并且考虑到ConfigurationManager.AppSettings[]索引器本身可能会爆,所以还得加try-catch,最终代码就变成这样了:

try
{
string enableAzureWebTraceConfig = ConfigurationManager.AppSettings["EnableAzureWebTrace"];
if (!string.IsNullOrEmpty(enableAzureWebTraceConfig))
{
bool enableAzureWebTrace = false;
if (bool.TryParse(enableAzureWebTraceConfig, out enableAzureWebTrace) && enableAzureWebTrace)
{
// do some logic
}
else
{
throw new ConfigurationException("EnableAzureWebTrace value must be true of false.");
}
}
}
catch (ConfigurationException ce)
{
// error handling logic
throw;
}

这样的代码非常没有逼格,重用性很差,如果你的config里面AppSettings比较多,或者一个settings在程序里到处被用,显然不应该每次都把这样的代码到处复制。所以封装一下呗:

public bool IsEnableAzureWebTrace()
{
try
{
bool enableAzureWebTrace = false;
string enableAzureWebTraceConfig = ConfigurationManager.AppSettings["EnableAzureWebTrace"];
if (!string.IsNullOrEmpty(enableAzureWebTraceConfig))
{
if (!bool.TryParse(enableAzureWebTraceConfig, out enableAzureWebTrace))
{
throw new ConfigurationException("EnableAzureWebTrace value must be true of false.");
}
}
return enableAzureWebTrace;
}
catch (ConfigurationException ce)
{
// error handling logic
return false;
}
}

现在要用到EnableAzureWebTrace的地方都只要调用public bool IsEnableAzureWebTrace()就行了,我们就把如何读config的逻辑抽离了。重构的目的是,万一以后读config的机制变了,只要改这一处。不用到处改。但是,我们重构的粒度还不够。这个方法只能用来读EnableAzureWebTrace这一个设置。我们要通用一下,让它也能读其他bool类型的设置。把key单独的抽出来变成参数:

public bool GetBooleanConfiguration(string key)
{
try
{
bool val = false;
string rawConfigValue = ConfigurationManager.AppSettings[key];
if (!string.IsNullOrEmpty(rawConfigValue))
{
if (!bool.TryParse(rawConfigValue, out val))
{
throw new ConfigurationException(string.Format("{0} value must be true of false.", key));
}
}
return val;
}
catch (ConfigurationException ce)
{
// error handling logic
return false;
}
}

但是这还不够,因为这个方法只能满足于bool类型的config,我们希望有个公用的方法,能读取其他类型。这时候就需要用泛型了。把返回类型给抽离出来。
难点在于,每种数据类型的类型转换写法不一样。比如bool类型是bool.TryParse,int类型是int.TryParse,怎么把这部分逻辑抽象出来呢?
一种办法是用C#本身的类型转换:
(T) Convert.ChangeType(rawConfigValue, typeof (T));
另一种是把类型转换的逻辑作为委托加在方法的参数里,这样就用lambda表达式去传,我比较偏向这种方法,因为方法的调用者能非常清晰的知道“该干嘛,该怎么干”。
这时候,如果因为非法类型转换爆,是得让调用者知道的。所以我偏向把TryParse改为Parse,死就要死个明白。
public T GetConfiguration<T>(Func<string, T> parseFunc, string key)
{
try
{
T val = default(T);
string rawConfigValue = ConfigurationManager.AppSettings[key];
if (!string.IsNullOrEmpty(rawConfigValue))
{
return parseFunc(rawConfigValue);
}
return val;
}
catch (ConfigurationException ce)
{
// error handling logic
return default(T);
}
}
现在,调用这个方法就能这样去写:
GetConfiguration<bool>(bool.Parse, "EnableAzureWebTrace");
看起来已经很牛逼了。但其实还不够。考虑到之前说的config值为空字符串的问题,安全一点的做法是,当遇到空字符串时候,返回一个默认值。因为这种错误,并不是key不存在的错误,而是key存在,但是值没填。非法值是应该认为错误的。但是空值我个人认为更应该处理为一种“警告”,是应该有fallback的策略的,而非不可饶恕的错误。为了返回默认值,我们可以多加一个委托。
public T GetConfiguration<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc, string key)
{
try
{
string rawConfigValue = ConfigurationManager.AppSettings[key];
return !string.IsNullOrEmpty(rawConfigValue) ?
parseFunc(rawConfigValue) :
defaultTValueFunc();
}
catch (ConfigurationException ce)
{
// error handling logic
return default(T);
}
}
现在,调用者就能灵活处理遇到config为空时候的默认值了:
GetConfiguration<bool>(bool.Parse, () => false, "EnableAzureWebTrace");
但是如果每次都在条件判断里写上面那样的语句是挺麻烦的,在一般的系统开发中,我们常常会用一个管理配置的Settings类来对应Web.config里的设置表,维护这个关系。为了使用方便,我们会把每个Settings的名字,也就是key,作为属性去暴露给调用者,于是你就能这样写:
public bool EnableAzureWebTrace
{
get
{
return GetConfiguration<bool>(bool.Parse, () => false, "EnableAzureWebTrace");
}
}
你以为装逼结束了吗?当然不行!你没发现,属性名称和传进去的string类型的key名称是重复的吗?这样写代码是不是有点蛋疼?而且最惨的是,在VS2015,C#6.0之前(也就是下版本的C#),string这种东西,要是写错了是编译不出来的,所以我们应该尽量避免用string传key。经常会发生改了属性名,没有一起改string值的悲剧。比如MVVM框架的RaisePropertyChanged(string)就经常坑爹(题外话)。。。
好在,.NET4.5有个CallerMemberName特性,意思是”调用我的方法叫什么名字”,就能帮我们把这个string参数撸掉。
所以,我们只需要把方法签名里的string key改成:
public T GetConfiguration<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc, [CallerMemberName]string key = "")
这样这个方法被调用的时候,key就会自动赋值为调用它的方法或属性名。然后,刚才的那个属性就能够这样去写:
public bool EnableAzureWebTrace
{
get
{
return GetConfiguration<bool>(bool.Parse, () => false);
}
}
你以为装逼真的结束了吗?还有最后一步。万一要是碰到有些情况,属性名真的和appSettings里的key名字不一样怎么办?为了灵活处理这种边缘情况,还可以加个参数,强撸这种名称不一样的情况,如果这个参数被赋值了(下面的supressKey),就用它去读config而不用传入 的key。
下面给出我博客里读AppSettings的通用代码:
private T TryGetValueFromConfig<T>(Func<string, T> parseFunc, Func<T> defaultTValueFunc,
[CallerMemberName]string key = "", string supressKey = "")
{
try
{
if (!supressKey.IsNullOrEmptyOrWhiteSpace())
{
key = supressKey;
}
var node = ConfigurationManager.AppSettings[key];
return !string.IsNullOrEmpty(node) ? parseFunc(node) : defaultTValueFunc();
}
catch (Exception ex)
{
Logger.Error(string.Format("Error Reading web.config on AppSettings node: {0}", key), ex);
return default(T);
}
}
现在,你就能灵活装逼了,给几个例子:
string类型,属性名和key不一样,默认值“FileSystemImageProvider”:
public string PostImageProvider
{
get
{
return TryGetValueFromConfig(_ => _, () => "FileSystemImageProvider", supressKey: "ImageProvider");
}
}
bool类型,默认值想要true
public bool IncludeSiteDomainForImageUploadUrl
{
get
{
return TryGetValueFromConfig(bool.Parse, () => true);
}
}
int类型,默认值为20
public int CacheSlideExpireTimeSpanFallbackMinutes
{
get
{
return TryGetValueFromConfig(int.Parse, () => 20);
}
}

 

 

 

 

自定义节点

namespace Configer
{
    /// <summary>
    /// 网站信息配置节点
    /// </summary>
    public class WebConfigSection : ConfigurationSection
    {
        /// <summary>
        /// 网站名称
        /// </summary>
        [ConfigurationProperty("WebName", DefaultValue = "", IsRequired = true, IsKey = false)]
        public string WebName
        {

            get { return (string)this["WebName"]; }
            set { this["WebName"] = value; }
        }
        /// <summary>
        /// 网站域名
        /// </summary>
        [ConfigurationProperty("DoMain", DefaultValue = "", IsRequired = true, IsKey = false)]
        public string DoMain
        {

            get { return (string)this["DoMain"]; }
            set { this["DoMain"] = value; }
        }

    }
}
namespace Configer
{
    /// <summary>
    /// 网站配置信息工厂
    /// </summary>
    public class WebConfigManager
    {
        /// <summary>
        /// 配置信息实体
        /// </summary>
        public static readonly WebConfigSection Instance = GetSection();

        private static WebConfigSection GetSection()
        {
            WebConfigSection config = ConfigurationManager.GetSection("WebConfigSection") as WebConfigSection;
            if (config == null)
                throw new ConfigurationErrorsException();
            return config;
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <!--一定要在第一个, 不然会出错-->
  <configSections>
    <section name="WebConfigSection" type="程序集.类, 程序集"/>
  </configSections>
  <WebConfigSection WebName="XXX" DoMain="XXXX"  />
  <appSettings>
    <add key="site" value="www.zzl.com"/>
  </appSettings>
</configuration>

 

 

 

 

 private Configuration readAppConfig()
        {
            string configPath = @"E:\xxx\App.config";
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration( new ExeConfigurationFileMap()
            {
                ExeConfigFilename = configPath
            }, ConfigurationUserLevel.None);

            //MessageBox.Show(config.AppSettings.Settings["serverIp"].Value);
            return config;
        }

 

 
posted @ 2017-12-29 09:19  `Laimic  阅读(270)  评论(0)    收藏  举报