ASP.NET WebConfig
ASP.NET WebConfig設定
<compilation debug="true" targetFramework="4.0" /> debug 開啟目標Framwork 4.0以上需要指定
Customer Errors 自定義錯誤
有一些屬性可以開啟
mode 啟用或者停用自定義錯誤
On 啟用指定自定義錯誤 如未指定defaultRedirect則只會看到一般錯誤,如指定則 錯誤會回傳給客戶端以及本地主機
Off 禁用指定自定義錯誤 詳細錯誤會顯示給客戶端以及本地主機
RemoteOnly 指定將自定義錯誤顯示給遠端客戶端詳細的ASP錯誤則只回報給主機,此為預設值
redirectMode 指定顯示自定義錯誤時如何處理原本的URL
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors>
此為當發生未指定錯誤時進入到GenericErrorPage發生403時指定到NoAccess發生404時指定到FileNotFound
身分驗證
<authentication mode="Windows"/>要注意當使用Web時要把Windows改成Forms
<authentication mode="Forms">
連接字串
<connectionStrings>
<add name="Sales"
connectionString=
"server=myserver;database=Products;
uid=<user name>;pwd=<secure password>" />
</connectionStrings>
name 字串名稱
connectionString = "server = server名稱(IP) ;database = database名稱;
userID = 登入DB的userID; password = password"
沒記錯的話少password會產生問題沒辦法登入,SQL記得設password,不要用windows認證
類別庫如何讀取MVC專案的web.config
手法一
web.config中 建立 appSettings 或者 connectionStrings
差別在於connectionStrings是以
<add name="名稱" connectionString="Data Source=服務器名;Initial Catalog=DataBase名稱;User ID=用戶名;Password=密碼" providerName="System.Data.SqlClient" />
或
<add name="名稱" connectionString="server=伺服器名;database=DataBase名稱;User ID=用戶名;Password=密碼" providerName="System.Data.SqlClient" />
appSettings
第二點有點不太明白,推測可能是不用寫DataSource=讀出來的DataSet
可能可以直接DataBind()然後在前端直接<#bind(DataColumnName)>
接著可以用using System.Configuration
來讀取 SqlConnection name = new SqlConnection(ConfigurationManager.ConnectionStrings["name"]).
ConnectionString;
如果跳出錯誤,則有可能是預設未加入System.Configuartion.dll的參考
加入即可使用
在類別庫中定義參數
這個用法的好處在於,可以有一個視覺化的工具幫你管理你的參數,另一個優點是你可以在程式碼中以強型別存取參數
點選之後會出現一個白色視窗,點選裡面後會可以建立參數
settings.settings就是那個視覺化的工具,可以幫你產生參數,而Designer.cs則是產生的程式碼
,由於是自動產生的,因此不要隨意更改
建立一個參數
則settings.Designer.cs中則會出現
並且可以使用
string stringname = Properties.Settings.Default.someDb;
來調用他,而stringname原本也可以先預設值,這樣就算無法調用someDb也不會為空。
接著app.config中
是跟web.config中很像的xml檔案
首先先在Configuration中設定configSections(config區段)
接著設定第一個sectionGroup(區段群組) 包含name和section中的name
並且在sectionGroup 的name 中設定name , serializeAS="type" 和 value=""
即可完成連線設定,同樣的可以把這些字串搬進web.config中
參考
https://blog.miniasp.com/post/2015/11/23/How-Class-library-read-config-from-webconfig-or-appconfig-file
留言
張貼留言