MVC 解读WebConfig

一、webconfig概述

系统的梳理一下webconfig各个节点的含义

<?xml version="1.0" encoding="utf-8"?>
<!--有时候webconfig中配置的节点较多,这时候可以将一些节点剥离出去单独写,然后引用,比如下面的<appSettings/>和<connectionStrings>
-->

<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->

<!--configuraion是根节点,所有的配置内容都在configuration内进行-->
<configuration>

<!--指定配置节和命名空间声明,配置节和配置节组定义在configSections-->
<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 configSource="connectionStrings.config" />

<!--appSettings是应用程序设置,可以定义应用程序的全局变量等信息--> 
<appSettings configSource="appSettings.config" /> 

<!--控制ASP.NET运行时的行为-->
<system.web>
<!--identity控制应用程序的身份验证标识-->
<identity impersonate="true" userName="Administrator" password="123" />

<!--通过 <authentication> 节可以配置 ASP.NET使用的安全身份验证模式,以标识传入的用户。Windows: 使用IIS验证方式,
Forms: 使用基于窗体的验证方式,Passport: 采用Passport cookie验证模式,None: 不采用任何验证方式
-->
<authentication mode="Forms"> 
<forms name="MVCDemo" cookieless="UseCookies" loginUrl="~/Account/Auth/Login" protection="All" timeout="2880"/> 
<!--Name: 指定完成身份验证的Http cookie的名称。LoginUrl: 如果未通过验证或超时后重定向的页面URL,一般为登录页面,让用户重新登录。
Protection: 指定 cookie数据的保护方式,可设置为:All表示加密数据并进行有效性验证两种方式,None表示不保护Cookie,
Encryption表示对Cookie内容进行加密,validation表示对Cookie内容进行有效性验证。TimeOut: 指定Cookie的失效时间,超时后要重新登录。
-->
</authentication> 

<!--默认错误页设置.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> 
<!-- 设置 compilation debug="true" 将调试符号插入已编译的页面中。但由于这会影响性能,因此只在开发过程中将此值设置为 true。
设置默认的开发语言C#。batch是否支持批处理-->
<compilation debug="true" defaultLanguage="c#" batch="false" targetFramework="4.5.2">
<assemblies>
<!--加的程序集引用,每添加一个程序集,就表示你的应用程序已经依赖了一个程序集,你就可以在你的应用程序中使用了-->
<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> 
</assemblies>

<!--定义用于编译自定义资源文件的生成提供程序的集合。-->
<buildProviders> 
<add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/>
</buildProviders> 
</compilation>
<pages validateRequest="false" controlRenderingCompatibilityVersion="5.0" enableViewState="false" enableSessionState="false" enableEventValidation="false">
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>


<!--配置asp.net http运行库的设置。可以在计算机,站点,应用程序和子目录级别声明
允许最多的请求个数100,最长允许执行请求时间为80秒,控制用户上传文件的大小,默认是4M。
useFullyQualifiedRedirectUrl客户端重定向不需要被自动转换为完全限定格式。-->
<httpRuntime appRequestQueueLimit="100" executionTimeout="80" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false" targetFramework="4.5.2" />

<!--httpModules在一个应用程序内配置 HTTP 模块。-->
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>

<!--为 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>
<!--该节替换在 httpHandlers 和 httpModules 节中添加的与 AJAX 相关的 HTTP 处理程序和模块。
该节使 IIS 7.0 在集成模式下运行时可使用这些处理程序和模块。在iis7.0 下运行 ASP.NET AJAX 需要 system.webServer 节。
对早期版本的 IIS 来说则不需要此节。-->
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" />
</compilers>
</system.codedom>
</configuration>

二、常见配置解析

上边我们已经把具体的webconfig内容详细介绍了一遍,上边也说了,有时候webconfig中配置的节点较多,这时候可以将一些节点剥离出去单独写,然后引用,比如<appSettings/>和<connectionStrings>

剥离出来的<appSettings/>文件如下: 

<?xml version="1.0" encoding="utf-8"?>
<appSettings >  
  <!--RabbitMQ服务[Begin]-->
  <add key="RabbitMQHostUri" value="tcp://127.0.0.1:20001/RabbitMQHost" />
  <!--RabbitMQ服务[End]-->
  <add key="webpages:Version" value="3.0.0.0" />
  <add key="webpages:Enabled" value="false" />
  <add key="PreserveLoginUrl" value="true" />
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  <add key="WebSiteSqlServerDAL" value="MVC.DB.SqlServer.DAL" />      
</appSettings>

剥离出来的<connectionStrings>文件如下:  

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
  <clear />
  <add name="MvcDataConstr" connectionString="Server=.;Initial Catalog=MvcData;User ID=sa;Password=123" providerName="System.Data.SqlClient" />
</connectionStrings>

附张图吧,其实位置都无所闻,只要指定好就行

三、自定义节点 

大部分情况下,我们都是在<appsetting>中定义自己需要的参数,简单方便。如果配置的参数比较多,比较复杂的话就会显得杂乱无章,而且这种方式不支持复杂的层次节点也不支持强类型,所以有时候我们需要自定义节点。下面我们以配置redis参数和lognet参数为例,介绍自定义节点。

1、配置redis节点  

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="RedisConfig" type="MyRedisConfigurationHelper.MyRedisConfigurationSection,MyRedisConfigurationHelper" />
    <section name="MyLog4net" type="MyLogConfigHelper.MyLog4netClass,MyLogConfigHelper"/>
  </configSections>
  <RedisConfig autoStart="true" dbIndex="0" password="redispass123" allowAdmin="true" abortConnect="false">
    <ReadWriteHost>
      <add host="127.0.0.1:6379" />
    </ReadWriteHost>
    <ReadOnlyHost>
      <add host="192.168.4.110:6379" />
    </ReadOnlyHost>
    <MaxWritePoolSize size="65000" />
    <MaxReadPoolSize size="65000" />
    <SocketSendTimeout second="1000" />
    <SocketReceiveTimeout second="1000" />
    <ConnectTimeout second="1000" />
  </RedisConfig>
  <MyLog4net>
    <add key="LogName" value="Test" />
    <add key="LogLevel" value="4" />
  </MyLog4net>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <appSettings>
    <add key="CACHE_REDIS" value="true" />    
  </appSettings>
  <system.web>
    <membership defaultProvider="ClientAuthenticationMembershipProvider">
      <providers>
        <add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" connectionStringName="DefaultConnection" credentialsProvider="" />
      </providers>
    </membership>
    <roleManager defaultProvider="ClientRoleProvider" enabled="true">
      <providers>
        <add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" connectionStringName="DefaultConnection" />
      </providers>
    </roleManager>
  </system.web>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source = |SQL/CE|" />
  </connectionStrings>
</configuration>

自定义配置节点需要注意的事项如下:

  • 自定义节点必须在configSections节点中。

  • section节点属性:name:必选的 String 属性,指定与 type 属性中指定的配置节处理程序关联的配置节或元素的名称。这是该元素在配置文件的节设置区域中使用的名称。type:必选的 String 属性,指定用来执行如下操作的配置节处理程序类的名称:处理在 name 属性中指定的节或元素中的配置设置。

  • section 元素将配置节处理程序与配置元素或节关联。每个 section 元素均标识一个配置节或元素。可以在 sectionGroup 元素中对 section 元素进行逻辑分组,以对 section 元素进行组织并避免命名冲突。section 和 sectionGroup 元素包含在 configSections 元素中。我们在这里没有介绍sectionGroup,毕竟在项目中自定义节点也不多,name不重复即可。

  • 具体的一些特性和元素解释可以参考官网https://docs.microsoft.com/zh-cn/previous-versions/ms228245(v=vs.110)

2、配置log4net节点

 

log4net相关的自定义配置信息解析    

<section name="MyLog4net" type="MyLog4netDemo.MyLog4netClass,MyLog4netDemo"/>

(1)其中name是配置文件中自定义节点设置区域使用的名称,就是标识设置具体自定义节点所使用的名称。比如:

<MyLog4net>
    <add key="LogName" value="Test" />
    <add key="LogLevel" value="4" />
  </MyLog4net>

(2)其中type中的MyLog4netClass就是自定义节点所需要的方法实现。针对于该自定义节点,实现方法如下:

using System;
using System.Configuration;

namespace MyLogConfigHelper
{
    /// <summary>
    /// 读取自定义配置文件信息
    /// </summary>
    public class MyLog4netClass : ConfigurationSection
    {
        private static readonly ConfigurationProperty property
        = new ConfigurationProperty(string.Empty, typeof(MyLog4netClassElementCollection), null,
                                        ConfigurationPropertyOptions.IsDefaultCollection);

        [ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
        public MyLog4netClassElementCollection KeyValues
        {
            get
            {
                return (MyLog4netClassElementCollection)base[property];
            }
        }

        #region 读取自定义配置文件信息
        private static MyLog4netClass _myLog4netClassProperty = null;
        public static MyLog4netClass MyLog4netClassProperty
        {
            get { return _myLog4netClassProperty; }
            set
            {
                _myLog4netClassProperty = value;
            }
        }
        static MyLog4netClass()
        {
            const string SETTINGS = "MyLog4net";
            object section = null;
            if (System.Web.Hosting.HostingEnvironment.IsHosted)
            {
                //web.config
                section = ConfigurationManager.GetSection(SETTINGS);
            }
            else
            {
                //App.config
                section = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).Sections[SETTINGS];
            }
            if (section is MyLog4netClass)
            {
                _myLog4netClassProperty = section as MyLog4netClass;
            }
            if (_myLog4netClassProperty == null)
            {
                throw new Exception("请在Config文件中配置<configSections> < section name ="MyLog4net" type="MyLog4netDemo.MyLog4netClass,MyLog4netDemo"/></configSections>");

            }
        }
        #endregion
    }

    /// <summary>
    /// 元素集合
    /// </summary>
    [ConfigurationCollection(typeof(MyLog4netClassElement))]
    public class MyLog4netClassElementCollection : ConfigurationElementCollection       
    {
        public MyLog4netClassElement this[int index]
        {
            get
            {
                return (MyLog4netClassElement)base.BaseGet(index);
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }
        /// <summary>
        /// 重写ConfigurationElementCollection中的方法
        /// <summary>
        /// <returns></returns>
        protected override ConfigurationElement CreateNewElement()
        {
            return new MyLog4netClassElement();
        }
        /// <summary>
        /// 重写ConfigurationElementCollection中的方法
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MyLog4netClassElement)element).Key;
        }
    }
    /// <summary>
    ///  集合中的每一个元素  实现MyLog4net集合中每一个元素的key  value
    /// </summary>
    public class MyLog4netClassElement : ConfigurationElement
    {
        public MyLog4netClassElement()
        {
        }
        public MyLog4netClassElement(string key,string value)
        {
            this.Key = key;
            this.Value = value;
        }
        [ConfigurationProperty("key", IsRequired = true)]
        public string Key
        {
            get
            {
                return (string)base["key"];
            }
            set
            {
                base["key"] = value;
            }
        }
        [ConfigurationProperty("value",IsRequired =true)]
        public string Value
        {
            get
            {
                return (string)base["value"];
            }
            set
            {
                base["value"] = value;
            }
        }
    }
}

(3)函数入口: 

using System;

namespace MyLogConfigHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            MyLog4netClass myLog4netClass = MyLog4netClass.MyLog4netClassProperty;
            foreach (MyLog4netClassElement item in myLog4netClass.KeyValues)
            {
                Console.WriteLine("key:{0}", item.Key);
                Console.WriteLine("Value:{0}", item.Value);
            }
            Console.ReadKey();
        }
    }
}

四、代码下载

其实就是对Element、ElementCollection、Section的操作

1、MyLog4net相关代码下载

2、RedisConfig相关代码下载

原文地址:https://www.cnblogs.com/qtiger/p/10033353.html