Home > other >  ASP.NET Core 6 Web API - making fields required
ASP.NET Core 6 Web API - making fields required

Time:01-03

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.

CodePudding user response:

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://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0

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

CodePudding user response:

It is because the [BsonId] requires the string to set.

For reference see the source code: https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Bson/Serialization/Attributes/BsonRequiredAttribute.cs

You should create a different model for your endpoint and map that model to your datamodel and populate the Id field with a value.

  • Related