Why does it say "The field is required" in postman even if it's nullable?

Viewed 60

I have connected my asp.net core project to MS SQL server and am trying to test my APIs after writing the controllers. Here are 2 of the data models that I am trying to use.

 public partial class Content
    {
        public Guid CCuid { get; set; }
        public Guid CPuid { get; set; }
        public string? CContents { get; set; }
        public decimal? CAmount { get; set; }
        public string? CCheckNumber { get; set; }
        public int? CQuantity { get; set; }
        public string? CNotes { get; set; }
        public DateTime CDateProcessed { get; set; }
        public string? CUserName { get; set; }
        public virtual Vompackage? CPu { get; set; } 
    }


 public partial class Package
      {
        public Package()
        {
            Contents = new HashSet<Content>();
        }
    
        /// <summary>
        /// Unique Package Identifier
        /// </summary>
        public Guid PPuid { get; set; }
        public Guid PSuid { get; set; }
        public string? PTrackingNumber { get; set; }
        public string? PBolnumber { get; set; }
        public string? PProductCode { get; set; }
        public int? PQuantity { get; set; }
        public int? PPallets { get; set; }
        public int? PBoxes { get; set; }
        public string? PNotes { get; set; }
        public DateTime PDateEntered { get; set; }
    
        public virtual Vomshipment? PSu { get; set; }
        public virtual ICollection<Content> Contents { get; set; }
    }
    }

Now I am trying to add a content using postman. When I tried to add the following data,

{
    "cAmount": 2332,
    "cCheckNumber": "",
    "cQuantity": 133,
    "cNotes": "thank u ",
    "cDateProcessed": "2020-12-02T13:40:47.207",
    "cUserName": "ztinsley",
    "CPu": null
    }
         

It gives 400 response, and

"errors": {
    "CPu": [
        "The CPu field is required."
    ]

I used null! to make CPu nullable. And when I tested GET method to pull all the contents, it says "cPu": null for every data. Why is it having trouble adding a new data? I also tried to add options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true in AddControllers(), but the it gives me 500 response. Please help!

P.S. I have attached my controller to see if I made any mistakes.

   [Produces("application/json")]
        [ApiController]
        [Route("api/content")]
        public class ContentController : Controller
        {
            private readonly IContentRepository _contentReporitory;
    
            public ContentController(IContentRepository contentReporitory)
            {
                _contentReporitory = contentReporitory;
            }
   [HttpGet("{ccuid}")]
        public async Task<ActionResult<Content>> GetContentById(Guid ccuid)
        {
            try
            {
                var result = await _contentReporitory.GetContentById(ccuid);

                if (result == null)
                {
                    return BadRequest();
                }

                return result;
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError,
                    "Error retrieving data from the database");
            }
        } 
            [HttpPost("addcontent")]
            public async Task<ActionResult<Content>> AddContent([FromBody]Content content)
            {
                try
                {
                    if (content == null)
                        return BadRequest();
    
                    var newContent = await _contentReporitory.AddContent(content);
    
                    return CreatedAtAction(nameof(GetContentById),
                        new { id = newContent.CCuid }, newContent);
    
    
                } catch (Exception)
                {
                    return StatusCode(StatusCodes.Status500InternalServerError);
                }
            }
    
        }
    }

My repository:

    public class ContentRepository : IContentRepository
    {
        private readonly OperationsContext _operationsContext;

        public ContentRepository(OperationsContext operationsContext)
        {
            _operationsContext = operationsContext;
        }

        public async Task<Content> AddContent(Content content)
        {
            var result  = await _operationsContext.Contents.AddAsync(content);
            await _operationsContext.SaveChangesAsync();
            return result.Entity;
        }


    }
}
1 Answers

All project templates starting with .NET 6 (C# 10) enable the nullable context for the project. Projects created with earlier templates don't include this element, and these features are off unless you enable them in the project file or use pragmas. It means CPu is treated as a non-nullable property.

So you can simply send {} instead of null:

{
    "cAmount": 2332,
    "cCheckNumber": "",
    "cQuantity": 133,
    "cNotes": "thank u ",
    "cDateProcessed": "2020-12-02T13:40:47.207",
    "cUserName": "ztinsley",
    "CPu": {}
    }

Or just set

public virtual Package? CPu { get; set; } 

Then you can send "CPu": null.

You can refer to this Docs to learn more.

Related