如何通过配置将字符串数组设置为枚举?

huangapple go评论71阅读模式
英文:

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:

&quot;Kestrel&quot;: {
  &quot;Endpoints&quot;: {
    &quot;Https&quot;: {
      &quot;Url&quot;: &quot;https://localhost:5003&quot;,
      &quot;SslProtocols&quot;: [ &quot;Tls12&quot;, &quot;Tls13&quot; ]
    }
  }
}

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:

&quot;HttpsEndpoint&quot;: {
  &quot;Url&quot;: &quot;https://localhost:5003&quot;,
  &quot;SslProtocols&quot;: [ &quot;Tls12&quot;, &quot;Tls13&quot; ]
}

I then have an HttpsEndpointOptions object:

public sealed class HttpsEndpointOptions
{
    public Uri Url { get; init; } = new UriBuilder(&quot;http&quot;, &quot;localhost&quot;, 5004).Uri;
    public SslProtocols SslProtocols { get; private set; } = SslProtocols.None;
}

I use GetSection(&quot;HttpsEndpoint&quot;).Get&lt;HttpsEndpointOptions&gt;() 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.

huangapple
  • 本文由 发表于 2023年3月4日 00:38:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定