ASPNET Core 3.0 Model validation error with Inheritance

Viewed 1010

I just moved to ASP.NET Core 3.0 and it seems that either model validation with inheritance is broken, or I am missing something. When I post the following model with IlVal00 = null, it says:

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 the following, it works:

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; }
}

But I need this to support inheritance. Does anyone have an idea for how to make this work?

Thanks.

2 Answers

As I went through a very close scenario, I will add here an answer just in case others run into the same or similar issues:

In my case, the problem involved a project with .NET Core 3.1 as Target Framework and inheritance was not part of the problem. My project had a NuGet package dll as one of its dependencies and such package had several models. Our controller endpoints had these models as parameters. However, requests sent to any of these endpoints (with any of those models as body) were giving rise to validation errors for non-nullable reference type properties.

The workaround to solve it was similar to the one suggested here: https://github.com/dotnet/aspnetcore/issues/14812. I added the following option to AddControllers method, from Startup's ConfigureServices method:

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

Note that, by using this workaround, it will be necessary to manually add [Required] attributes for nullable reference type properties around your application.

I also opened an issue on their repository: https://github.com/dotnet/aspnetcore/issues/27448

try to use virtual like this:

public virtual string? IlVal00 { get; set; }
Related