어떻게 정의 사용자 정의 웹입니다.config 섹션과 함께 잠재적인 아이의 요소 및 특성에 대한 속성?

StackOverflow https://stackoverflow.com/questions/2155

  •  08-06-2019
  •  | 
  •  

문제

웹 응용 프로그램 개발이 필요할 수 co-의존하는 구성 설정과도 있는 설정을 변경해야로 우리는 사이 우리 각자의 환경입니다.

우리의 모든 설정은 현재의 간단한 키 값 쌍 하지만 그것을 만드는 데 유용할 수 있 설정 섹션은 그래서 그것은 때 분명 두 값을 변경할 필요가 함께할 때 또는 설정을 변경할 필요한 환경.

최선의 방법은 무엇일을 만드는 설정 섹션은 없는 특별한 고려사항을 검색할 때 가치입니까?

도움이 되었습니까?

해결책

사용 특성,아이 config 섹션과 제약 조건

도있는 가능성 속성을 사용하여 자동으로 처리 배관공사뿐만 아니라,할 수있는 기능을 제공하 쉽게 추가 제약 조건이 있습니다.

나는 여기에 존재하는 예제 코드에서 나 자신을 사용하는에서 하나의 사이트입니다.제약조건으로 나를 지시 최대 디스크 공간 중 하나는 사용자가 사용합니다.

MailCenterConfiguration.cs:

namespace Ani {

    public sealed class MailCenterConfiguration : ConfigurationSection
    {
        [ConfigurationProperty("userDiskSpace", IsRequired = true)]
        [IntegerValidator(MinValue = 0, MaxValue = 1000000)]
        public int UserDiskSpace
        {
            get { return (int)base["userDiskSpace"]; }
            set { base["userDiskSpace"] = value; }
        }
    }
}

이 설정에서 웹.과 같이 config

<configSections>
    <!-- Mailcenter configuration file -->
    <section name="mailCenter" type="Ani.MailCenterConfiguration" requirePermission="false"/>
</configSections>
...
<mailCenter userDiskSpace="25000">
    <mail
     host="my.hostname.com"
     port="366" />
</mailCenter>

아동 요소

아이 xml element 메일 에서 만들어 동일합니다.cs 파일로 위의 하나입니다.여기에 내가 추가 제약 조건에서 포트가 있습니다.는 경우는 포트 값이 할당하지 않는 이 범위에서 런타임에 넋두리하면 config 이 로드됩니다.

MailCenterConfiguration.cs:

public sealed class MailCenterConfiguration : ConfigurationSection
{
    [ConfigurationProperty("mail", IsRequired=true)]
    public MailElement Mail
    {
        get { return (MailElement)base["mail"]; }
        set { base["mail"] = value; }
    }

    public class MailElement : ConfigurationElement
    {
        [ConfigurationProperty("host", IsRequired = true)]
        public string Host
        {
            get { return (string)base["host"]; }
            set { base["host"] = value; }
        }

        [ConfigurationProperty("port", IsRequired = true)]
        [IntegerValidator(MinValue = 0, MaxValue = 65535)]
        public int Port
        {
            get { return (int)base["port"]; }
            set { base["port"] = value; }
        }

그때 그것을 실제적으로 사용하는 코드에서,당신이해야 할 모든 것 인스턴스화 MailCenterConfigurationObject 이 자동으로 읽기 관련 부분을 웹에서.config.

MailCenterConfiguration.cs

private static MailCenterConfiguration instance = null;
public static MailCenterConfiguration Instance
{
    get
    {
        if (instance == null)
        {
            instance = (MailCenterConfiguration)WebConfigurationManager.GetSection("mailCenter");
        }

        return instance;
    }
}

AnotherFile.cs

public void SendMail()
{
    MailCenterConfiguration conf = MailCenterConfiguration.Instance;
    SmtpClient smtpClient = new SmtpClient(conf.Mail.Host, conf.Mail.Port);
}

체크 유효성

이전에 언급된 런타임을 때 불평 구성이드와 일부 데이터을 준수하지 않는 규칙을 설정(예:에 MailCenterConfiguration.cs).나는 알고 싶어하는 경향이 이러한 것들을 가능한 한 빨리 내 사이트를 발생 합니다.를 해결하는 하나의 방법이 짐을 구성에서 _Global.맨.cx.Application_Start_ 경우,구성이 잘못된 것이 통보와 의미의 예외입니다.귀하의 사이트에 시작되지 않고 대신 할 수 있는 상세한 예외에서 정보 노란색 화면 죽음의.

글로벌입니다.맨.cs

protected void Application_ Start(object sender, EventArgs e)
{
    MailCenterConfiguration.Instance;
}

다른 팁

빠른'n'더러운:

첫 번째 만들기 ConfigurationSectionConfigurationElement 클래스:

public class MyStuffSection : ConfigurationSection
{
    ConfigurationProperty _MyStuffElement;

    public MyStuffSection()
    {
        _MyStuffElement = new ConfigurationProperty("MyStuff", typeof(MyStuffElement), null);

        this.Properties.Add(_MyStuffElement);
    }

    public MyStuffElement MyStuff
    {
        get
        {
            return this[_MyStuffElement] as MyStuffElement;
        }
    }
}

public class MyStuffElement : ConfigurationElement
{
    ConfigurationProperty _SomeStuff;

    public MyStuffElement()
    {
        _SomeStuff = new ConfigurationProperty("SomeStuff", typeof(string), "<UNDEFINED>");

        this.Properties.Add(_SomeStuff);
    }

    public string SomeStuff
    {
        get
        {
            return (String)this[_SomeStuff];
        }
    }
}

다음 프레임워크를 처리하는 방법을 알고 당신의 구성에서 클래스 웹.config:

<configuration>
  <configSections>
    <section name="MyStuffSection" type="MyWeb.Configuration.MyStuffSection" />
  </configSections>
  ...

실제로 추가 자신의 아래 섹션:

  <MyStuffSection>
    <MyStuff SomeStuff="Hey There!" />
  </MyStuffSection>

다음 사용할 수 있습니다 그것은 코드에 따라서:

MyWeb.Configuration.MyStuffSection configSection = ConfigurationManager.GetSection("MyStuffSection") as MyWeb.Configuration.MyStuffSection;

if (configSection != null && configSection.MyStuff != null)
{
    Response.Write(configSection.MyStuff.SomeStuff);
}

에 대한 예 MSDNConfigurationCollection 다.NET4.5 사용자 지정 섹션은 웹에서.config 가 있는 목록의 구성 항목입니다.

사용자 지정 구성은 아주 편리한 것은 종종 응용 프로그램으로 끝날에 대한 수요는 확장 가능한 솔루션입니다.

습니다.NET1.1 참조하시기 바랍 문서 http://aspnet.4guysfromrolla.com/articles/020707-1.aspx

참고:위의 솔루션을 작동합니다.NET2.0 니다.

습니다.NET2.0 특정 솔루션을 참조하시기 바랍 문서 http://aspnet.4guysfromrolla.com/articles/032807-1.aspx

이 작업을 수행할 수 있습니다 섹션의 처리기입니다.가에 대한 기본적인 개요를 작성하는 방법 중 하나에 http://www.codeproject.com/KB/aspnet/ConfigSections.aspx 그러나 그것을 참조하는 앱입니다.config 는 것은 꽤 많이 쓰는 것과 같은 하나 웹에서 사용하기 위해.config.이것은 당신이 본질적으로 자신의 XML 트리 설정파일에서 앞에 몇 가지 더 진보된 구성이 있습니다.

가장 간단한 방법,내가 찾은 사용 appSettings 섹션.

  1. 추가 웹.config 다음과 같다:

    <appSettings>
        <add key="MyProp" value="MyVal"/>
    </appSettings>
    

  2. 에서 액세스 코드

    NameValueCollection appSettings = ConfigurationManager.AppSettings;
    string myPropVal = appSettings["MyProp"];
    

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top