将 OWin 相关属性放在 appSettings 中的另一种方法是编写自定义ConfigurationSection
. 这个类可以包含所有必要的管道。另外,XML 模式可以添加代码完成。
示例代码
public static class IAppBuilderExtensions {
public static void ApplyConfigSettings(this IAppBuilder appBuilder) {
var config = (OWinConfigSection) System.Configuration.ConfigurationManager.GetSection("owinConfig");
if (config == null) return;
if (config.GoogleAuthentication.Enabled) appBuilder.UseGoogleAuthentication();
}
}
public class OWinConfigSection : ConfigurationSection {
[ConfigurationProperty("GoogleAuthentication", IsRequired=false)]
public GoogleConfigurationElement GoogleAuthentication
{ get { return (GoogleConfigurationElement)this["GoogleAuthentication"]; } }
}
public class GoogleConfigurationElement : ConfigurationElement {
[ConfigurationProperty("Enabled", DefaultValue = "false", IsRequired = false)]
public bool Enabled
{ get { return (bool)this["Enabled"]; } set { this["Enabled"] = value; } }
}
将以下 XML 片段放入元素configSections
的 中:configuration
<section name="owinConfig" type="OWinConfigSection" requirePermission="false" />
然后,只需app.ApplyConfigSettings();
在 OWin 启动期间调用某处。
示例架构
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="XMLSchema1" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="owinConfig_T">
<xs:all minOccurs="0">
<xs:element name="GoogleAuthentication" type="GoogleAuthentication_T" />
</xs:all>
</xs:complexType>
<xs:complexType name="GoogleAuthentication_T">
<xs:attribute name="Enabled" use="optional" default="false">
<xs:annotation>
<xs:documentation>Set to true to enable Authentication via Google OAuth</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
<xs:element name="owinConfig" type="owinConfig_T" />
</xs:schema>