23

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Aneef
  • 3,641
  • 10
  • 43
  • 67

4 Answers4

26

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);
Aneef
  • 3,641
  • 10
  • 43
  • 67
16

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);
raddevus
  • 8,142
  • 7
  • 66
  • 87
JapaTechFoss
  • 161
  • 2
  • JapaTechFoss, this largely looks like an answer. But the "?" in the last line confuses me. You are trying to answer according to [answer], aren't you? – Yunnosch Feb 28 '22 at 15:24
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – mohammad mobasher Feb 28 '22 at 22:00
  • 1
    The string? refers to dot net 6 introducing explicit nullability for things that were already implicitly nullable. His answer refers to making the strings explicitly nullable by suffixing the type with a question mark. Hence nullable string. There isn't anything wrong with his answer as far as I can see. – dyslexicanaboko Jan 02 '23 at 21:29
12

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

Jaleel
  • 603
  • 2
  • 8
  • 18
0

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.

klekmek
  • 533
  • 3
  • 11
  • 1
    it does, when saving to the MongoDB. but not in the model. also it works fine with .net 5 – Aneef Jan 03 '22 at 07:27