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


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成員資格定義用戶身份驗證,只可在機器級和應用程序級重寫

1 <membership 
2   defaultProvider="MyMemberShip"//可選屬性,默認為AspNetSqlProfileProvider 
3   userlsOnlineTimeWindow="number of minutes" //可選屬性,指定賬戶的上次活動時間戳之后的分鍾數,在這段時間 內,該用戶被視為處於聯機狀態,默認是15分鍾
4   hashAlgorithmType="SHA1"> //可選屬性,指定對密碼值的加密算法,該值對應於cryptoNameMapping節中nameEntry元素的                              name屬性。默認為SHA1.
5 <providers>
6   <add name="MyMemberShip" type="MyMemberShip" requiresQuestionAndAnswer="true" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=....">
7   </providers>
8 </membership>
membership 節點
 1 // 必須實現MembershipProvider虛擬類的所有成員方法
 2 public class MymemberShip : MembershipProvider
 3     {
 4         private string appName = "TestMembershipProvider";
 5         //設置密碼問題
 6         private bool _requiresQuestionAndAnswer;
 7         //最小密碼長度
 8         private int _minRequiredPasswordLength;
 9         public MymemberShip()
10         { //構造函數邏輯
11         }
12         string connectionString = "...";
13         public override string ApplicationName
14         {
15             get
16             { return appName; }
17             set
18             { appName=..; }
19         }
20         
21         //驗證用戶
22         public override bool ValidateUser(string username, string password)
23         {
24             using (OleDbConnection conn=new OleDbConnection(connectionstring))
25             {
26                 OleDbCommand comm = new OleDbCommand();
27                 comm.CommandText = "select count(0) from users where u_name=@name and u_pwd=@pwd";
28                 comm.Parameters.AddWithValue("@name",username);
29                 comm.Parameters.AddWithValue("@pwd", password);
30                 comm.Connection = conn;
31                 conn.Open();
32                 return ((int)comm.ExecuteScalar())>0?true:false;
33                 
34             }
35         }
36         //修改密碼
37         public override bool ChangePassword(string username, string oldPassword, string newPassword)
38         {
39             using (OleDbConnection conn=new OleDbConnection(connectionString))
40             {
41                 OleDbCommand comm = new OleDbCommand();
42                 //最后改成參數化,以防Sql注入
43                 comm.CommandText = "update users set u_pwd='" + newPassword + 
44                     "'where u_name='" + username + "'and u_pwd='" + oldPassword + 
45                     "'";
46                 comm.Connection = conn;
47                 if (conn.State==ConnectionState.Closed)
48                 {
49 
50                 }
51 
52             };
53         }
54     }
代碼

mobileControls:列出web控件的設備特有的類適配器
pages:頁面的控件特性
processModel:配置進程模型
profile:定義用戶配置文件數據模型的設置,只可在機器級和應用程序級重寫

 1 <profile
 2  enabled="true" 是否啟用profile
 3  inherits="fully qualified type reference"包含從ProfileBase抽象類派生的自定義類型的類型引用
 4  automaticSaveEnabled="true"指定頁面執行完自動保存profile
 5  defaultProvider="SqlProfileProvider">配置文件提供程序名默認為AspNetSqlProfileProvider
 6  <properties>必選元素,定義profile屬性和屬性組集合.</properties>
 7    <add name="Name" serializeAs="Xml"/>//在程序中對屬性賦值,就會自動記錄到數據庫
 8           <add name="Pwd" serializeAs="Xml"/>
 9  <providers>可選元素,定義配置文件提供程序的集合.
10           <add name="SqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="SqlConnectionString" applicationName="/" />
11  </providers>
12 </profile>
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>
role manager 節點

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>
View Code

 

在程序中取出配置值的語句是: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();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM