不可为空的字符串类型,如何使用 with Asp.Net 核心选项

Non-nullable string type, how to use with Asp.Net Core options

MS 状态 Express your design intent more clearly with nullable and non-nullable reference types

我的意图是表达,我的 JwtOptions 中的属性 IssuerAudience 永远不会为空。这些选择对于消费者来说哪个是非常合理的意图,不是吗?这些非空值由下面描述的 Asp.Net 核心验证来确保。

但是如果 JwtOptions 没有构造函数初始化所有属性,那么 C# 8 编译器报告

Warning CS8618 Non-nullable property 'Issuer' is uninitialized.

并且出于某些技术原因,Asp.Net 核心选项不能具有带参数的构造函数。所以我坚持我的意图。我可以关闭可为空检查或声明 Issuer 和其他属性可为空,但我认为这不是最佳解决方案。

这种情况有什么优雅的解决方案吗?

来自 csproj 的代码段:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  <LangVersion>8.0</LangVersion>
  <Nullable>enable</Nullable>
</PropertyGroup>

我在 Asp.Net 核心应用程序中有这些强类型选项:

public class JwtOptions
{
    [Required]
    public string Issuer { get; set; }

    [Required]
    public string Audience { get; set; }

}

选项由 Startup.cs 中的下一个代码配置:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddOptions<JwtOptions>()
            .Bind(Configuration.GetSection("JwtOption"))
            .ValidateDataAnnotations();
    }

并被 HomeController 消费:

    public HomeController(IOptions<JwtOptions> options)
    {
        string audience = options.Value.Audience;
        string issuer = options.Value.Issuer;
    }

如您所见,AudienceIssuer 对于消费者都不能为 null。使这些属性可为空没有意义。

据编译器所知,还没有初始化,可以null。使用 !(null-forgiving operator) 作为最后的手段(并发表评论解释为什么使用 !

// This should be set by the options binding
public string Issuer { get; set; } = null!;