반응형
한번 정해지면 변하지 않는 것을 상수라고 한다.
그러한 상수를 전역적으로 사용하기 위해서, Web.config를 이용하면 된다.
appSettings 를 이용하자.
1
2
3
4
5
6
7
8
9
10
|
<appSettings>
<add key="appKey" value="1234567"/>
<add key="appCode" value="cmang9"/>
<add key="appVisible" value="true"/>
</appSettings>
<connectionStrings>
<add name="REAL" connectionString="Data Source=ServerName;User Id=id;PASSWORD=password;Initial Catalog=DatabaseName" providerName="System.Data.SqlClient" />
<add name="TEST" connectionString="Data Source=ServerName;User Id=id;PASSWORD=password;Initial Catalog=DatabaseName" providerName="System.Data.SqlClient" />
</connectionStrings>
|
cs |
appSettings 노드 안에 자식 노드를 여러 key/value 값으로 추가할 수 있다.
일반적인 전역상수를 제외하고, DB를 연결할 수 있는 connectionString도 Web.config에서 관리할 수 있다.
BehindCode에서 Web.config 상수 호출 방법
1
|
var appKey = ConfigurationManager.AppSettings["appKey"];
|
cs |
간단하다. key값을 넣어주면 value값을 리턴해준다. Dictionaly 와 비슷하다.
1
|
var connectionString = ConfigurationManager.ConnectionStrings["REAL"].ConnectionString;
|
cs |
connectionString도 다르지 않다. 여기에는 name 값을 넣어주면 된다.
부모-자식 형태의 상수 설정 방법
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<configSections>
<sectionGroup name="cmang9">
<section name="information" type="System.Configuration.NameValueSectionHandler"/>
<section name="etc" type="System.Configuration.NameValueSectionHandler"/>
</sectionGroup>
</configSections>
<cmang9>
<information>
<add key="name" value="jack"></add>
<add key="age" value="50"></add>
<add key="address" value="incheon"></add>
</information>
<etc>
<add key="job" value="programmer"></add>
</etc>
</cmang9>
|
cs |
appSettings 이외의 다른 노드도 생성이 가능하다. configSections 에 부모-자식 Group으로 생성한 것을 네이밍해주면 된다. 나는 key/value를 사용하기 위해서 type을 위에와 같이 설정해주었다.
BehindCode에서 상수 호출 방법
1
2
3
4
5
6
7
|
var age = GetSection["age"];
var address = GetSection["address"];
// 속성
private NameValueCollection GetSection {
get => (NameValueCollection)ConfigurationManager.GetSection("cmang9/information");
}
|
cs |
간단하게 속성을 지정하여 호출하면 된다.
반응형
'개발 > ASP.NET' 카테고리의 다른 글
[ASP.NET] 업로드 파일 용량을 web.config에서 제어하자. (0) | 2019.12.04 |
---|---|
[ASP.NET] 라우팅(Routing) 이란? (0) | 2019.12.04 |
Server.Transfer VS Response.Redirect 차이를 알아보자. (0) | 2019.12.04 |
[ASP.NET] Global.asax 을 알아보자. (2) | 2019.12.04 |
[ASP.NET] 404 / 500 Error 일때, Web.config를 사용하자! (1) | 2019.12.04 |