asp.net 配置文件(Machine.config、Web.config、App.config)

来源:互联网 发布:君子去仁 恶乎成名翻译 编辑:程序博客网 时间:2024/05/19 18:00

Machine.config
1.该文件在Windows目录下\Microsoft.net\framework\[version]\Config\
2.为了提高性能,该文件只包含不同于默认值的设置。并且定义了配置文件项可包含的配置节,就像是一个基础的定义。可以使用System.Configuration命名空间中的类读取配置文件
3.Configuration元素的主要子元素
appSettiongs:包含自定义的应用程序设置
configSections:申明自定义设置的配置节。如果该元素存在,必须是configuration节                          点的第一个子节点。它可以直接包含sectionGroup和section子节。
                        sectionGroup用于标记和组织几个子节,通常表示要应用配置设置的
                        命名空间。name属性表示正在声明的节名称,type属性指示从配置文
                        件读取该节内容并对它进行解析的托管类的名称,值是一个逗号隔开id
                        字符串,包括类和包含它的程序集的全名。还有三个专用元素
                        add,remove,clear(清除以前的设置,即不继承)
connectionStrings:列出对应用程序有用的预定义的连接字符串
configProtectedData:包含已被加密的配置节的加密数据
runtime:运行时设置架构,描述那些配置程序集绑定和运行时行为的元素,比如               probing和assembly redirect
startup:启动设置架构,包含那些规定必须使用哪个版本的公共语言运行库的元素
system.diagnostics:描述那些规定跟踪开关和监听器(收集、存储和传递消息)的元素
system.net:网络架构,规定那些指示.net framework如何连接到Internet的元素,包括默认的代理、身份验证模块和连接参数
system.runtime.remoting:设置架构,配置利用.net remoting的客户端和服务端应用程序
system.web:包含那些控制asp.net应用程序的各方面行为的元素
4.system.web元素的主要子元素
anonymousIdentification:配置未经身份验证的用户的标识,只可在机器级和应用程序级重写
authentication:设置身份验证机制,只可在机器级和应用程序级重写
authorization:指示已授权的用户
browserCaps:列出已知的浏览器能力
clientTarget:列出已预定义的客户目标
compilation:批编译的设置
customErrors:自定义的错误页面设置,只能在Machine.config或一级web.config文件中设置,不能多重继承
deployment:指示如何部署应用程序
deviceFilters:列出已知的移动浏览器能力
globalization:用于应用程序本地化设置
healthMonitoring:配置一个用于运行状况监视的应用程序,只可在机器级和应用程序级重写
hostingEnvironment:定义控制应用程序承载环境的行为的配置,只可在机器级和应用程序级重写
httpCookies:配置cookie的属性
httpHandlers:列出已注册的http处理程序
httpModules:列出已注册的http模块
httpRuntime:列出http运行库设置
identity:设置个性化
machineKey:敏感数据的加密密钥
membership:通过asp.net成员资格定义用户身份验证,只可在机器级和应用程序级重写

复制代码
<membership 
  
defaultProvider="MyMemberShip"//可选属性,默认为AspNetSqlProfileProvider 
  userlsOnlineTimeWindow
="number of minutes" //可选属性,指定账户的上次活动时间戳之后的分钟数,在这段时间                                               内,该用户被视为处于联机状态,默认是15分钟
  hashAlgorithmType
="SHA1"> //可选属性,指定对密码值的加密算法,该值对应于cryptoNameMapping节中nameEntry元素的                              name属性。默认为SHA1.
<providers>
  
<add name="MyMemberShip" type="MyMemberShip" requiresQuestionAndAnswer="true" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=....">
  
</providers>
</membership>
复制代码

 

 

复制代码
// 必须实现MembershipProvider虚拟类的所有成员方法
public class MymemberShip : MembershipProvider
    {
        
private string appName = "TestMembershipProvider";
        
//设置密码问题
        private bool _requiresQuestionAndAnswer;
        
//最小密码长度
        private int _minRequiredPasswordLength;
        
public MymemberShip()
        { 
//构造函数逻辑
        }
        
string connectionString = "...";
        
public override string ApplicationName
        {
            
get
            { 
return appName; }
            
set
            { appName
=..; }
        }
        
        
//验证用户
        public override bool ValidateUser(string username, string password)
        {
            
using (OleDbConnection conn=new OleDbConnection(connectionstring))
            {
                OleDbCommand comm 
= new OleDbCommand();
                comm.CommandText 
= "select count(0) from users where u_name=@name and u_pwd=@pwd";
                comm.Parameters.AddWithValue(
"@name",username);
                comm.Parameters.AddWithValue(
"@pwd", password);
                comm.Connection 
= conn;
                conn.Open();
                
return ((int)comm.ExecuteScalar())>0?true:false;
                
            }
        }
        
//修改密码
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            
using (OleDbConnection conn=new OleDbConnection(connectionString))
            {
                OleDbCommand comm 
= new OleDbCommand();
                
//最后改成参数化,以防Sql注入
                comm.CommandText = "update users set u_pwd='" + newPassword + 
                    
"'where u_name='" + username + "'and u_pwd='" + oldPassword + 
                    
"'";
                comm.Connection 
= conn;
                
if (conn.State==ConnectionState.Closed)
                {

                }

            };
        }
    }
    
复制代码

 

mobileControls:列出web控件的设备特有的类适配器
pages:页面的控件特性
processModel:配置进程模型
profile:定义用户配置文件数据模型的设置,只可在机器级和应用程序级重写

复制代码
<profile
 
enabled="true" 是否启用profile
 inherits
="fully qualified type reference"包含从ProfileBase抽象类派生的自定义类型的类型引用
 automaticSaveEnabled
="true"指定页面执行完自动保存profile
 defaultProvider
="SqlProfileProvider">配置文件提供程序名默认为AspNetSqlProfileProvider
 
<properties>必选元素,定义profile属性和属性组集合.</properties>
   
<add name="Name" serializeAs="Xml"/>//在程序中对属性赋值,就会自动记录到数据库
          
<add name="Pwd" serializeAs="Xml"/>
 
<providers>可选元素,定义配置文件提供程序的集合.
          
<add name="SqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="SqlConnectionString" applicationName="/" />
 
</providers>
</profile>
复制代码

 

protocols:规定asp.net web服务能使用的协议,只可在机器级和应用程序级重写
roleManager:定义角色管理的设置,只可在机器级和应用程序级重写

复制代码
<roleManager cacheRoleslnCookie="true|false"
  cookieName
="name" cookiePath="/"
  cookieProtection
="All|Encryption|Validation|None
  cookieRequireSSL="
true|false"
  cookieSlidingExpiration
="true|false"
  cookieTimeout
="number of minutes"
  createPersistentCookie
="true|false"
  defaultProvider
="provider name"
  domain
="cookie domain"
  enabled
="true|false"
  maxCachedResults
="maximum number of role names cached">
<provider></provider>
</rolemanager>

//location节点设置用户角色访问权限,对应的API类是ConfigurationLocation,可通过此类读取配置信息
<location path="admin.aspx">
  
<system.web>
    
<authorization>
      
<allow roles="admin"/>
      
<deny users="*"/>
    
</authorization>
  
</system.web>
</location>
<location path="guest.aspx">
  
<system.web>
    
<authorization>
      
<allow roles="guest"/>
      
<deny users="*"/>
    
</authorization>
  
</system.web>
</location>
<location path="changePassword.aspx">
  
<system.web>
    
<authorization>
      
<deny users="?"/>//拒绝匿名用户
    
</authorization>
  
</system.web>
</location>
复制代码

 

securityPolicy:定义允许的信任级别,只可在机器级和应用程序级重写
sessionState:配置Session对象,只可在机器级和应用程序级重写
siteMap:定义用来支持导航基础结构的设置,只可在机器级和应用程序级重写
trace:配置跟踪系统
trust:定义默认的信用级别,只可在机器级和应用程序级重写
webControls:定位客户端脚本
webParts:定义Web Parts的设置
webServices:配置Web服务
xhtmlConformance:定义xhtml一致性的设置

 

Web.Config
1.必须包含在<Configuration></Configuration>标记对中。此文件包括2部分,第一部分是模块处理方式声明,包含在<Configsections></Configsections>标记对中;第二部分才是真正的设置内容:
<configuration>
  <configSections>
    <section name="appSettings" type="System.Web.Configuration.NameValueSectionHandler"/>
    <section name="sessionState" type="System.Web.Configuration.SessionStateConfigHandler"/>
  </configSections>
  <appSettings>
    <add key="key" value="value"/>
  </appSettings>
</configuragion>

2.应用程序专用设置

复制代码
<?xml version="1.0"?>
<configuration >
  
<configSections>
    
<section name="database" type="System.Web.Configuration.DictionarySectionHandler"/>
  
</configSections>
  
<database>
    
<add key="edu" value="server=.;uid=sa;pwd='';database='edu'"/>
  
</database>
</configuration>
复制代码

 

在程序中取出配置值的语句是:Context.GetConfig("key")("value")
3.中文显示,如果要求整个站点都显示中文,则将Web.Config文件放在根目录下
  <system.web>
    <globalization requestEncoding ="UTF-8" responseEncoding ="UTF-8"/>
  </system.web>
4.Session超时设置,注意该设置只能在根目录即全局中定义
 <system.web>
    <sessionState cookieless ="false" timeout ="30"/>
  </system.web>
5.authentication节:Forms,Windows,Passport,None
loginUrl验证失败时重定向到的Url,如果重定向到其他机器,两台机器的decryptionKey属性必须相同;name指定用于验证的cookie名称;timeout指定cookie超时分钟数,缺省是30。由于cookie在超时时间过一半时可能被刷新(根据浏览器的设置),所以timeout不一定准确;path指定cookie路径;protection指定对cookie保护类型。
authentication节中可包含一个credentials节,该节可输入用户名和密码信息。
6.authorization节,通过allow节和deny节来控制用户权限
7.customErrors节来控制错误信息怎么显示
8.httpHandlers节规定应用程序使用哪些http处理器;httpModules节
9.identity节控制应用程序的身份标识
10.pages节包含页面专有的信息
11.processModel节控制IIS进程模式设置
12.sessionState节控制怎样管理会话状态
13.trace节设置跟踪服务,可在代码中使用Trace类的Write()方法在跟踪输出中添加自定义的信息。

 

对配置文件的操作:
1.对web.config里的连接字符串加密解密
使用命令行工具aspnet_regiis 

//获取当前登录用户
currentUser=System.Security.Principal.WindowsIdentity.GetCurrent().Name//name是需要加密
string name=@"connectionStrings";
string appPath="/testconfiguration";
//打开Web.config文件
Configuration config=WebConfigurationManager.OpenWebConfiguration (appPath);
//提供加密的方法
string provider="RsaProtectedConfigurationProvider";
//Rsa加密方法需要打开加密容器,语法是aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT AUTHORITY\Network service(也可以是currentUser)"
//设置加密节点
config.GetSection(name).SectionInformation.ProtectSection(provider);
//解密
//config.GetSection(name).SectionInformation.UnProtectSection();
//保存文件
config.Save();
2,添加节点
string name=@"system.web/httpHandlers";
//指定虚拟路径
string appPath="/testconfiguration";
//打开Web.config文件
Configuration config=WebConfigurationManager.OpenWebConfiguration (appPath);
//获取system.web/httpHandlers配置节
HttpHandlersSection section=(HttpHandlersSection)config.GetSection(name);
//定义子节点
HttpHandlersAction newHandle=new HttpHandlerAction("*.aaa","System.Web.HttpForbiddenHandler","*");
//添加子节点
section.Handlers.Add(newHandle);
//移除子节点section.Handlers.Remove("*","*.aaa");
config.Save();
0 0
原创粉丝点击