不可为空的字符串类型,如何与Asp.Net Core选项一起使用 [英] Non-nullable string type, how to use with Asp.Net Core options
问题描述
MS指出使用nullable可以更清楚地表达您的设计意图和非空引用类型.
我的意图是表达我的JwtOptions
中的属性Issuer
和Audience
永远不会为空.对于这些选项的消费者来说,哪个是非常合理的意图,不是吗?这些非空值由下面描述的Asp.Net Core验证来确保.
My intent is to express, that properties Issuer
and Audience
in my JwtOptions
are never null. Which is very reasonable intent for consumers of these options, is not? These not null values are ensured by Asp.Net Core validation described below.
但是,如果JwtOptions
的构造函数未初始化所有属性,那么C#8编译器将报告
But if JwtOptions
has not all properties initialized by the constructor, so C# 8 compiler reports
警告CS8618不可初始化的属性'Issuer'未初始化.
Warning CS8618 Non-nullable property 'Issuer' is uninitialized.
由于某些技术原因,Asp.Net Core选项不能具有带参数的构造函数.所以我坚持自己的意图.我可以关闭可为空的检查,或者声明Issuer
和其他可为空的属性,但是我认为这不是最好的解决方案.
And for some technical reasons, Asp.Net Core options cannot have a constructor with parameters. So I am stuck with my intent. I can switch nullable checking off or declare Issuer
and other properties nullable, but I think this is not the best solution.
在这种情况下,是否有任何优雅的解决方案?
Is there any elegant solution in this case?
csproj的片段:
Snippet from csproj:
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
我在Asp.Net Core应用程序中具有以下强类型选择:
I have these strongly typed options in Asp.Net Core application:
public class JwtOptions
{
[Required]
public string Issuer { get; set; }
[Required]
public string Audience { get; set; }
}
选项由Startup.cs中的下一个代码配置:
Options are configured by a next code in 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.使这些属性可为空是没有道理的.
As you can see, nor Audience
nor Issuer
cannot be null for the consumer. Make these properties nullable makes no sense.
推荐答案
据编译器所知,它尚未初始化,可以null
.将!(null-forgiving operator)
作为最后的手段(并在注释中说明您使用!
的原因.
As far as the compiler knows, it has not been initialized and can be null
. Use the !(null-forgiving operator)
as a last resort (and leave a comment explaining why you used !
.
// This should be set by the options binding
public string Issuer { get; set; } = null!;
这篇关于不可为空的字符串类型,如何与Asp.Net Core选项一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!