17

I have been working on a project that uses .NET 6.0 and SQL and have been running into a status: 400 title: "One or more validation errors occurred." error whenever I try to make a POST request for my Treatments table as shown below (using Swagger).

400 - Undocumented
Error: response status is 400

Response body
Download
{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-471d5fa9b5bd60df0f6dddef0dcd44ad-4ed5f5f29428b83e-00",
  "errors": {
    "TblPet": [
      "The TblPet field is required."
    ],
    "Procedure": [
      "The Procedure field is required."
    ]
  }
}
Response headers
 content-type: application/problem+json; charset=utf-8 
 date: Thu,14 Jul 2022 11:25:42 GMT 
 server: Kestrel 

The project follows this ERD:

enter image description here

The API was scaffolded using Visual Studio 2022 which created many public virtual items that are most likely a result from all the foreign keys that have been set. As a result, my GET requests would return the data for the specified table AND data from Foreign Key tables, so I have been using the [JsonIgnore] data annotation within the models to prevent this from happening which has been a solution so far.

The Treatments model class looks like this:

using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace api.Models
{
    public partial class TblTreatment
    {
        public int Ownerid { get; set; }
        public string Petname { get; set; } = null!;
        public int Procedureid { get; set; }
        public DateTime Date { get; set; }
        public string? Notes { get; set; }
        public string? Payment { get; set; }
        [JsonIgnore]
        public virtual TblProcedure Procedure { get; set; } = null!;
        [JsonIgnore]
        public virtual TblPet TblPet { get; set; } = null!;
    }
}

With [JsonIgnore], the response body for the POST request looks like this, which is the response body that I would like. Maybe removing the payment section would be a good idea as each procedure already has a preset price and will not be changed during the POST request so by providing the procedureid, the API should automatically associate the price with the procedure. But again, I'm not too sure:

{
  "ownerid": 1,
  "petname": "Buster",
  "procedureid": 1,
  "date": "2022-07-14T11:25:31.335Z",
  "notes": "Broken Nose",
  "payment": "24"
}

However, without it, it looks like this, which requests data input for Treatments, Procedure table and Pets table as they have foreign keys attached to them:

{
  "ownerid": 0,
  "petname": "string",
  "procedureid": 0,
  "date": "2022-07-14T11:41:34.382Z",
  "notes": "string",
  "payment": "string",
  "procedure": {
    "procedureid": 0,
    "description": "string",
    "price": 0
  },
  "tblPet": {
    "ownerid": 0,
    "petname": "string",
    "type": "string"
  }

The POST request for the Treatments controller is as follows:

[HttpPost]
public async Task<ActionResult<List<TblTreatment>>> AddTreatment(TblTreatment treatment)
{
    _context.TblTreatments.Add(treatment);
    await _context.SaveChangesAsync();

    return Ok(await _context.TblTreatments.ToListAsync());
}

This format for POST requests have been working for my other controllers but not for the Treatments controller and I am not sure why. I suspect that the issue may be caused by the all foreign keys associated with the Treatments table, as the error is requesting data inputs for the foreign key tables (which I do not want to input). I am at a complete loss as to what needs to be changed.

Any advice on this would be greatly appreciated.

4
  • 2
    I would recommend not to use entities as models and introduce some DTOs which will represent only needed data in concrete scenario and map them from/to entities (to reduce amount of code you can use some library for example automapper for this). This way you can prevent such scenarios and also other problems like overposting and so on.
    – Guru Stron
    Commented Jul 14, 2022 at 13:26
  • That's a good point. I didn't even know that was an option. I will definitely take on board your advice for future projects. Thanks again, Guru Stron.
    – Kilo
    Commented Jul 14, 2022 at 17:00
  • I'm not Serge, but you are welcome)
    – Guru Stron
    Commented Jul 14, 2022 at 17:01
  • 1
    Sorry, thank you for your advice Guru Stron
    – Kilo
    Commented Jul 14, 2022 at 17:03

2 Answers 2

43

since you are using net6 ALL NOT REQUIRED properties should be nullable explicitly. So you should try this

        public string? Petname { get; set; } 
        public int? Procedureid { get; set; }
        [JsonIgnore]
        public virtual TblProcedure? Procedure { get; set; } 
        [JsonIgnore]
        public virtual TblPet? TblPet { get; set; }

or another way is that you can remove a nullable option from a project file

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

or add this line into config (startup or program)

services.AddControllers(
options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true
2
  • 3
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes might be the single longest boolean property within the framework. And it is exactly what I needed. Upgrading from NET5 NET6 and enabling nullable in my project files caused this issue, but it went unnoticed until I started regression testing against old API endpoints. So at that point I had a hell of time tracing it back to this. Thanks for the answer! Commented Sep 30, 2022 at 20:11
  • +1 for comprehensive answer with 3 possible approaches. My use case involves consuming models from a .net standard nuget package, so explicitly nullable properties isn't an option. Removing the nullable option is overkill, it's a feature I want in the rest of the project and the startup approach also didn't work, possibly because of the models' source. Any other ideas? I've had to specify query parameters individually and make them nullable for now. Commented Dec 7, 2023 at 11:16
0

as a note for others finding this post, we had the problem in our Azure APIs (same error), Suddenly - after a release with no changes that should introduce this error.

(pipelines for different environment have the same setup, code is the same... )

My colleague told me they had a similar error a year ago, API worked in production and acceptance but not in dev/test

I was about to set the controller option "SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true" but found the newtonsoft option "NullValueHandling.Ignore;" in our startup and disabled the option.

.AddNewtonsoftJson(options =>
                {
                   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                });

The API worked again (the strange thing was that we had working API in dev environment but not in production and it wasn't possible to replicate on local machine.

Then uncommented the code (reverting it) and API still works after deploy... Confusing 😂

then I installed the same build again, the one not wokring, to see if we just needed a reinstall or restart - but the error was back.

I haven't validated yet but my theory is that the reason could be that we get different build-agents from azure, we are currently using "windows 2022" but not specifying the dotnet version with build step "Use .NET Core" and SDK version, f ex sdk 6.0.300

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.