我有一个 web api,我已经按照以下链接在 web.config 中添加了一个自定义部分:https ://msdn.microsoft.com/en-us/library/2tw134k3.aspx 。我的 web.config 如下所示:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please
visit https://go.microsoft.com/fwlink/?LinkId=301879
-->
<configuration>
<configSections>
<sectionGroup name="productGroup">
<section
name="product"
type="myProject.Stuff.Api.ProductSection"
allowLocation="true"
allowDefinition="Everywhere"
/>
</sectionGroup>
</configSections>
<appSettings>
<!-- various app settings -->
</appSettings>
<productGroup>
<product name="my name" id="1" />
<product name="my name 2" id="2" />
</productGroup>
<!-- other standard elements -->
</configuration>
我在 configSections 和 productGroup 中添加了。然后我将 ac# 类定义为 ProductSection,如下所示:
使用 System.Configuration;
namespace myProject.Stuff.Api
{
public class ProductSection : ConfigurationSection
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return (string)this["name"];
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("id", IsRequired = true)]
public int Id
{
get
{
return (int)this["id"];
}
set
{
this["id"] = value;
}
}
}
}
我已经将这两个部分复制到我的测试项目中的 app.config 中,但是当我现在尝试调试测试时,我得到了初始化失败的错误。当我注释掉 productGroup 部分时,它就会停止抱怨。我做错了什么?
更新
作为旁注,我最终将它的结构更简单一些。由于我的“产品”部分只需要一个名称和 ID,因此它们根据 appSettings 借给键值对。所以我创建了一个这样的部分:
<configSections>
<section name="productGroup"
type="System..Configuration.NameValueSectionHandler"
allowLocation="true"
allowDefinition="Everywhere"/>
</configSections>
请注意,我更改了类型。我的 productGroup 然后看起来像这样:
<productGroup>
<add key="product1" value="1" />
<add key="product2" value="2" />
</productGroup>
然后我可以完全删除 ProductSection 类,并像这样引用我的产品组:
var products = ConfigurationManager.GetSection("productGroup") as NameValueCollection;
if (products.AllKeys.Contains(myProduct))
{
var myValue = products[myProduct];
}