英文:
How can you set a string array to an enum via config?
问题
在.NET Core配置中,您可以使用配置选项(config options),将配置中的一个部分映射到一个对象。对于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始终保持默认值。所以我想象中需要做一些映射工作。然而,我无法在选项对象中执行此操作,因为该对象在使用配置之前就已创建。是否有一种方法可以实现这个映射?
英文:
In .net core configuration you cap use config options, which maps a section in the config to an object. For Kestrel this seems to happen automatically. The bit I'm interested particularly is the 'SslProtocols' where you can state the protocols required in a string[]
like this:
"Kestrel": {
"Endpoints": {
"Https": {
"Url": "https://localhost:5003",
"SslProtocols": [ "Tls12", "Tls13" ]
}
}
}
If I wanted to create this manually using IOptions how could I map the SslProtocols string array to the enum? I've tried something like this:
"HttpsEndpoint": {
"Url": "https://localhost:5003",
"SslProtocols": [ "Tls12", "Tls13" ]
}
I then have an HttpsEndpointOptions object:
public sealed class HttpsEndpointOptions
{
public Uri Url { get; init; } = new UriBuilder("http", "localhost", 5004).Uri;
public SslProtocols SslProtocols { get; private set; } = SslProtocols.None;
}
I use GetSection("HttpsEndpoint").Get<HttpsEndpointOptions>()
to map it, but the SslProtocols always remain as the default. So I imagine there's some mapping I need to do. However, I can't do this in the options object as that is created before the configuration is used. Is there a way to do this?
答案1
得分: 0
看起来配置支持将逗号用作标志枚举的分隔符。所以我可以使用“Tls1, Tls2”作为示例。这将转换为 SslProtocols.Tls1 | SslProtocols.Tls2
。
英文:
Looks like the configuration supports using commas as delimiters for flag enums. So I was able to use "Tls1, Tls2" for example. This converted to SslProtocols.Tls1 | SslProtocols.Tls2
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论