2011-03-16 6 views
4

나는 방금 asp.net의 web.Config에서 값을 쓰고 값을 동적으로 추가하여 읽기를 생각해 냈습니다. 마음에 많은 아이디어가 있지만, 나는 단지 웹 설정에서 동적으로 값을 추가하는 가장 좋은 방법은 무엇인지 알고 있습니다. 동적으로 웹 설정에 값을 추가 하시겠습니까? How To + Best way

내 경우 예를 들어 난 뒤에 코드에서 웹 설정에

태그에

<identity userName="someDomain\User" password="password" impersonate="true" /> 

을 추가해야합니다.

왜 코드에서 ID를 설정하려고 좋은 반응

답변

5

이 항상

* web.config 
* machine.config 
* global.asax 
* Anything in the bin directory or it's sub-directories 

를 다시 시작합니다 다음과 같은 응용 프로그램에서 변경을 수행하여

당신과 당신이 원하는 코드는 다음과 같습니다

public void saveIdentity(string username, string password, bool impersonate) 
    { 
     Configuration objConfig = WebConfigurationManager.OpenWebConfiguration("~"); 
     IdentitySection identitySection = (IdentitySection)objConfig.GetSection("system.web/identity"); 
     if (identitySection != null) 
     { 
      identitySection.UserName = username; 
      identitySection.Password = password; 
      identitySection.Impersonate = impersonate; 
     } 
    objConfig.Save(); 
} 
+0

좋습니다. 나는 이미 그것을 발견했다 =). 같은 솔루션 .. 덕분에 – Singleton

+0

언제든지 환영합니다 :)이 작업에 문제가있는 사람은 – Marwan

+0

에게 문의하십시오. 응용 프로그램 풀이 파일을 수정할 수 있도록 "로컬 시스템"ID로 실행되어야 함을 명심하십시오. 시스템. – Illuminati

1

을 기다리고? 이것은 일반적으로 앱을 배포하고 나서 방치 할 때 앞에 설정해야하는 항목입니다. 성취하려는 것을 설명 할 수 있다면 더 나은 방법을 제안 할 수 있습니다.

그 외에도 웹 설정을 변경하면 앱이 다시 시작됩니다. 모든 서버 측 캐싱이 덤프되고 사용자 세션이 종료됩니다. 코드에서 웹 구성을 수정하는 도구가 존재한다고해서 그렇게하는 것이 좋지는 않습니다.

+0

나는 코드면에서 이것을 추가해야한다는 것을 알고있다. – Singleton

+0

그런 경우 나는 당신에게 진짜 제안이 없다는 것을 두려워합니다. 내가 아는 모든 것은 이것을하지 않는다고 말한다. 쇠망침을 사용하여 손톱을 움직이는 것과 비슷하지만 작업이 완료 될 수도 있지만 그 과정에서 무언가를 깨기 쉽습니다. 나는 누군가가 이것을하기의 적당한 방법으로 생각해 내는지 보는 것에 흥미가있을 것이다. – Rozwel

4

동적으로 web.config를 업데이트하지 않는 것이 좋습니다. 이렇게하면 응용 프로그램이 다시 시작되고 사용자 세션이 만료됩니다. 자세한 사항은 내가 가진 모습을 aspnet-application-restarts.html

+0

@Akhtar : 나는 그 사실을 알고 있고, 사용자 세션은 내 끝에서 문제가 아님 =) – Singleton

+1

물론 싱글 톤입니다. – Illuminati

1

이 데스크톱 응용 프로그램에 있지만 웹 응용 프로그램에서 사용할 수 있습니다.

if (Convert.ToInt32(txtPortNumber.Text.Trim()) <= 65535) 
{ 

    System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 

    System.Net.Configuration.MailSettingsSectionGroup mailSection = config.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup; 

    mailSection.Smtp.From = txtFrom.Text.Trim(); 
    mailSection.Smtp.Network.Host = txtFrom.Text.Trim(); 
    mailSection.Smtp.Network.UserName = txtFrom.Text.Trim(); 
    mailSection.Smtp.Network.Password = txtPassword.Text.Trim(); 
    mailSection.Smtp.Network.EnableSsl = chkEnableSSL.Checked; 
    mailSection.Smtp.Network.Port = Convert.ToInt32(txtPortNumber.Text.Trim()); 
    config.Save(ConfigurationSaveMode.Modified); 
    MessageBox.Show("Your mail setting has been saved successfully."); 
    Application.Restart(); 
} 
else 
{ 
    MessageBox.Show("Port number is not valid, please enter port number between the 0 to 65535."); 
}