Aspnetcore: AspNetCore 3.0 Model validation bug with Inheritance ?

Created on 8 Oct 2019  路  5Comments  路  Source: dotnet/aspnetcore

Hi, I've just moved to AspNetCore 3.0 and it seems that model validation with inheritance is broken or I miss something. When I'm posting the following model with IlVal00 = null, it say : title=One or more validation errors occurred. status=400, The IlVal00 field is required.

public class Stock : BaseClass
{
        [Required]
        public string Ref { get; set; } = default!;
}

public class BaseClass
{
        public string? IlVal00 { get; set; }
}

But if I change my model to that:

public class Stock : BaseClass
{
        [Required]
        public string Ref { get; set; } = default!;

        public new string? IlVal00 { get; set; }
}

public class BaseClass
{
        public string? IlVal00 { get; set; }
}

It works.
Did i miss something or it is a bug?
Thanks

Done area-mvc bug

Most helpful comment

It seems a bug. It is only causing when nullable references enabled.

Workaround:
set MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; and manually add [Required] attributes for nullable reference type properties.

All 5 comments

It seems a bug. It is only causing when nullable references enabled.

Workaround:
set MvcOptions.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; and manually add [Required] attributes for nullable reference type properties.

System.Runtime.CompilerServices.NullableAttribute attribute is not returning for properties in base class. Probably this is a bug related to C# 8.0 compiler.

https://github.com/aspnet/AspNetCore/blob/c565386a3ed135560bc2e9017aa54a950b4e35dd/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/ModelAttributes.cs#L139

Thanks for contacting us, folks.
@pranavkm can you please look into this? Thanks!

@mkArtakMSFT @pranavkm I have created a clear issue here. https://github.com/dotnet/roslyn/issues/39133.

Thanks for the issue report. For 3.0.0, @pavinan's suggestion would be the way to workaround this. We're addressing the underlying bug in 3.1.0

Was this page helpful?
0 / 5 - 0 ratings