ASP.NET Core 6 Web API - making fields required

Viewed 4808

I had a basic CRUD API which saves a model to a MongoDB which was working fine.

The model looks like the below:

[BsonIgnoreExtraElements]
public class Configuration
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [Display(Name = "Parameter Name")]
    [Required]
    public string ParamName { get; set; }
    [Display(Name = "Parameter Value")]
    [Required]
    public string ParamValue { get; set; }
    public string Description { get; set; }
}

And my action looks like this:

[HttpPost(Name = "Create")]
[Produces("application/json")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<ApiResult>> Create(Configuration configuration)
{
        try
        {
            var res = await _configurationRepository.Add(configuration);
            // DO OTHER STUFF
        }
        catch (Exception ex)
        {
            //error handling stuff
        }
}

When I ported this code to .NET 6, I try the above through Postman, but I get this error:

"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"The Id field is required."

Any idea why this happens? The same happens for string fields too. This is just an example basically most of my actions doesn't work due to this change.

4 Answers

2 possible work arounds:

builder.Services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

or change all string types to string? from the Configuration class.

There are 3 options to resolve this. You could try any one of these to make it work:

  1. Check whether your csproj file has the entry <Nullable>enable</Nullable>. If yes, remove it .

  2. Change public string Id { get; set; } to public string? Id { get; set; }

3.Add this line into Program.cs

builder.Services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);

--Cheers

Related