Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 6 Web API - making fields required

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.

like image 974
Aneef Avatar asked Sep 10 '25 17:09

Aneef


2 Answers

This is due to some model validation changes in ASP.Net 6 (Non Nullable Reference types)

Was able to resolve this by doing the below:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
like image 115
Aneef Avatar answered Sep 13 '25 06:09

Aneef


2 possible workarounds:

Workaround 1

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

Workaround 2

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

Extra Note

Additionally - AddControllersWithViews() may be called with this same options setting. For example:

builder.Services.AddControllersWithViews(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
like image 31
JapaTechFoss Avatar answered Sep 13 '25 04:09

JapaTechFoss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!