在 .net core 配置中,您可以使用配置选项,它将配置中的部分映射到对象。对于 Kestrel 来说,这似乎是自动发生的。我特别感兴趣的是“SslProtocols”,您可以在其中声明
string[]
中所需的协议,如下所示:
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:5003",
"SslProtocols": [ "Tls12", "Tls13" ]
}
}
}
如果我想使用 IOptions 手动创建它,如何将 SslProtocols 字符串数组映射到枚举?我尝试过这样的事情:
"HttpsEndpoint": {
"Url": "https://localhost:5003",
"SslProtocols": [ "Tls12", "Tls13" ]
}
然后我有一个 HttpsEndpointOptions 对象:
public sealed class HttpsEndpointOptions
{
public Uri Url { get; init; } = new UriBuilder("http", "localhost", 5004).Uri;
public SslProtocols SslProtocols { get; private set; } = SslProtocols.None;
}
我使用
GetSection("HttpsEndpoint").Get<HttpsEndpointOptions>()
来映射它,但 SslProtocols 始终保留为默认值。所以我想我需要做一些映射。但是,我无法在选项对象中执行此操作,因为该对象是在使用配置之前创建的。有办法做到这一点吗?
看起来配置支持使用逗号作为标志枚举的分隔符。所以我可以使用“Tls1,Tls2”为例。这转换为
SslProtocols.Tls1 | SslProtocols.Tls2
。