简体   繁体   English

.NET Core 2.2:仅当对象不为 null 时才验证 [required] 属性

[英].NET Core 2.2: Validate [required] properties only when object is not null

I have a complex model with nested objects.我有一个带有嵌套对象的复杂模型。 I only want my [Required] attributes to be validated when the object they are on is not null .我只希望我的[Required]属性在它们所在的对象不为null时得到验证。 So, for example, if I have a Home class with an Address property, the Home.Address.Street property should only be [required] if the Address is not null .因此,例如,如果我有一个带有Address属性的Home类,则Home.Address.Street属性应该仅在Address不为null时才为[required]

Code代码

In ASP.NET Core, I have a model that looks like this:在 ASP.NET Core 中,我有一个如下所示的模型:

public class Home
{
    [Required]
    public int Number {get;set;}
    public Address Address {get;set;} // This is not required
}
public class Address
{
   [Required]
   public string Street {get;set;}
   public IFormFile Picture {get;set;}

}

In a controller, I have an action method that looks like this:在控制器中,我有一个如下所示的操作方法:

[HttpPost]
public string AddHomes([FromForm]List<Home> homes) 
{
    if(!ModelState.IsValid)
    {
        return BadRequest();
    }
    // Do some saving
    return Ok();  
}

And the form payload looks like:表单有效负载如下所示:

homes.Index: 0
homes[0].number: 1

In ASP.NET Core 2.2, the first Home in the homes list is marked as invalid, but it was working as I would expect in ASP.NET Core 2.1.在 ASP.NET Core 2.2 中, homes列表中的第一个Home被标记为无效,但它在 ASP.NET Core 2.1 中的工作方式与我预期的一样。

What I want is for the [Required] attribute to only be validated if the Address is not null .我想要的是仅当Address不为null时才验证[Required]属性。 So a Home can either have an Address with a Street or no Address at all.因此,一个Home可以有一个Address和一个Street ,也可以根本没有Address

Is this achievable in .NET Core 2.2?这在 .NET Core 2.2 中可以实现吗?


Note: I've included an updated example below to reproduce error.注意:我在下面包含了一个更新的示例以重现错误。 It seems that the inclusion of IFormFile causes the Address class to initialize itself.似乎包含IFormFile会导致Address类自行初始化。

{
    "errors": {
        "homes[0].Address.Street": [
            "The Street field is required."
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "80000009-0003-ff00-b63f-84710c7967bb"
}

I also opened an issue on GitHub for this some time ago, if anybody wants to follow up: Inclusion of IFormFile property forces the whole object to be validated.前段时间我还在 GitHub 上为此打开了一个问题,如果有人想跟进: Inclusion of IFormFile property forces the whole object to be validated。 ASP.NET Core 2.2 . ASP.NET 核心 2.2

The behavior you're wanting is the behavior for null reference properties, and it has not changed in ASP.NET Core 2.2.您想要行为是空引用属性的行为,它在 ASP.NET Core 2.2 中没有改变。 The properties on the referenced class are only validated if the reference itself is non-null.仅当引用本身为非空时,才会验证引用类的属性。 If this isn't working for you, then the only conclusion is that this reference property does have a value.如果这对您不起作用,那么唯一的结论是这个引用属性确实有一个值。 It might just be a default instantiation (ie new Foo() ), with none of the sub properties actually defined, but that is enough to trigger validation.它可能只是一个默认实例化(即new Foo() ),实际上没有定义任何子属性,但这足以触发验证。

First, ensure that you are not setting a default value for the property, or otherwise providing it a default through the contructor, for example.首先,确保您没有为该属性设置默认值,或者通过构造函数等方式为其提供默认值。 In other words, if you have something like:换句话说,如果你有类似的东西:

public Bar Bar { get; set; } = new Bar();

Or,要么,

public Foo()
{
    Bar = new Bar();
}

Remove that.删除它。

Also, realize that if anything is posted for that reference property, then everything comes into play.此外,请注意,如果为该引用属性发布了任何内容,那么一切都会起作用。 Even if you just have some hidden property like:即使您只有一些隐藏属性,例如:

<input type="hidden" asp-for="Bar.Id" />

If any one property on the reference is posted, even if it, itself, is not valid, all validation on the class will come into play.如果引用的任何一个属性被发布,即使它本身无效,所有对类的验证都会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 .Net Core 2.2 绑定 - model 属性为 null - .Net Core 2.2 binding - model properties are null 在ASP.Net Core 2.2中,复杂对象以NULL的形式出现在HttpPut中 - Complex object is coming as NULL for HttpPut in ASP.Net Core 2.2 为什么在等待呼叫后需要等待呼叫(.NET Core 2.2) - Why am I required to await a call when it's already been await'ed (.NET Core 2.2) 验证数据库 ASP .NET Core 2.2 中是否已存在输入 - Validate if input already exist in database ASP .NET Core 2.2 502.3 在 .NET Core 2.2 中调用 AcquireTokenAsync 时 - 502.3 when calling AcquireTokenAsync in .NET Core 2.2 .NET Core 2.2中的DDD实体从属性中获取 - DDD entities in .NET Core 2.2 Get from properties asp.net core 2.2中嵌套属性的模型绑定 - Model binding of nested properties in asp.net core 2.2 如何在.Net core 2.2中为自定义属性配置AutoMapper? - How to configure AutoMapper in .Net core 2.2 for custom properties? ASP。 带有 cookie 身份验证的 Net Core 2.2:当未授权 API 仅控制器时如何避免页面重定向 - ASP. Net Core 2.2 with cookie authentication: how to avoid page redirect when not authorized for API only controllers .net Core 2.2 EF:SaveChangesAsync() 将不相关的列设置为空 - .net Core 2.2 EF: SaveChangesAsync() setting unrelated columns to null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM