gpt4 book ai didi

c# - 不可为空的字符串类型,如何与 Asp.Net Core 选项一起使用

转载 作者:行者123 更新时间:2023-12-03 15:09:41 24 4
gpt4 key购买 nike

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

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

但如果 JwtOptions没有由构造函数初始化的所有属性,因此 C# 8 编译器报告

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



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

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

来自 csproj 的片段:
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>

我在 Asp.Net Core 应用程序中有这些强类型选项:
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;
}

如您所见,也不是 Audience也不是 Issuer消费者不能为空。使这些属性可以为空是没有意义的。

最佳答案

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

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

关于c# - 不可为空的字符串类型,如何与 Asp.Net Core 选项一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54973037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com