为什么Aspnet.Core模型验证不会在Nullable属性上引发异常?

问题描述 投票:0回答:1

C#中的以下代码将引发InvalidOperationException,因为未设置时不允许访问Value。

int? a = null;
Console.Writeline(a.Value);

我在AspNet.Core中具有以下代码:

public class Request
{
    [Range(10, 20]
    public int? Field1 {get; set;}

    [Range(10, 20]
    public MyStruct Field2 {get; set;}
}

public struct MyStruct
{
    public int Value => throw new Exception();
}

[当模型验证发生时,框架会引发异常,因为它试图读取MyStruct的所有属性,并且显然无法读取Value。但是,如果我只有空字段,即使Value也抛出异常,验证也可以正常工作。

是否有一些仅被硬编码为不可为空的魔术,或者有某种方式可以使我的代码具有相同的行为?即我希望验证不为我的课程抛出异常。

[我怀疑这是硬编码的检查,还是某种语法糖,使得Nullable结构可以赋值并与null进行比较。

c# asp.net-core model-validation
1个回答
0
投票

如果您查看RangeAttribute的reference source,您会在IsValid方法的开头看到它:

// Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
if (value == null) {
    return true;
}

所以这是设计使然。就像注释所建议的那样,如果您具有可为null的类型并想要确认是否有值,则应使用RequiredAttribute。

public class Request
{
    [Required]
    [Range(10, 20]
    public int? Field1 {get; set;}

    [Range(10, 20]
    public MyStruct Field2 {get; set;}
}
© www.soinside.com 2019 - 2024. All rights reserved.