ASP.NET 引用项目中的自定义配置部分不起作用

本文关键字:自定义 配置部 不起作用 NET 引用 项目 ASP | 更新日期: 2023-09-27 17:57:20

我创建了一个继承自System.Configuration.ConfigurationSection的自定义类,像这样实现(这显然只是为了让真正的配置运行):

public class Config : ConfigurationSection
{
    [ConfigurationProperty("quoteOfTheDay", DefaultValue = "It is what it is.", IsRequired = false)]
    public string QuoteOfTheDay
    {
        get
        {
            return this["quoteOfTheDay"] as string;
        }
    }
    [ConfigurationProperty("yourAge", IsRequired = true)]
    public int YourAge
    {
        get
        {
            return (int)this["yourAge"];
        }
    }
}

该类的完整命名空间 + 名称是 MyApp.Core.Config,它位于编译为 MyApp.Core.dll 程序集的 MyApp.Core 项目中。然后,我从我的 ASP.NET/MVC3 项目中引用了这个项目,该项目称为MyApp.UI。我已经编辑了Web.config文件以添加sectionGroupsection元素,如下所示:

  <configSections>
    <sectionGroup name="myAppConfigGroup">
      <section name="myAppSection" 
           type="MyApp.Core.Config, MyApp.Core, Version=1.0.0.0, Culture=neutral, PublicKey=null" 
           allowLocation="true" 
           allowDefinition="Everywhere" />
    </sectionGroup>
  </configSections>
  <myAppConfigGroup>
    <myAppSection>
    </myAppSection>
  </myAppConfigGroup>
但是,在

我编辑配置时,似乎MyApp.Core.Config用于验证配置或提供智能感知的类型。以下是我所做的一些观察:

  • 我将 yourAge 属性定义为 IsRequired = true,没有它,应用程序运行良好。
  • 我什至可以在 <section> 元素中更改类型(更改为某种甚至不存在的类型,如 Foo.Bar),一切仍然运行良好
  • 但是,如果我删除 <section> 元素,应用程序将无法运行。

我很困惑,有什么帮助吗?

ASP.NET 引用项目中的自定义配置部分不起作用

您可能没有使用配置?如果您不使用它,它只会检查根节点是否通过configSections注册,但此时不会查看详细信息。

当您实际使用 ConfigurationManager.GetSection 加载它时,将验证设置,对于此配置,它将触发异常,告知缺少所需的 YourAge 属性。