Search code examples
c#asp.net-coreentity-framework-coreasp.net-core-webapi

Returns 400 Bad Request by POST, PUT methods but GET is working okay


I am trying to call POST/PUT method (by using HttpClient, in Swagger or Postman and it works) but it returns 400 status code. It checks for database connection and returns 200, so all is fine with that.

info: Microsoft.EntityFrameworkCore.Database.Command[20101]
  Executed DbCommand (27ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
  SELECT 1
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
  Executed DbCommand (42ms) [Parameters=[], CommandType='Text', CommandTimeout='30']

  IF EXISTS
      (SELECT *
       FROM [sys].[objects] o
       WHERE [o].[type] = 'U'
       AND [o].[is_ms_shipped] = 0
       AND NOT EXISTS (SELECT *
           FROM [sys].[extended_properties] AS [ep]
           WHERE [ep].[major_id] = [o].[object_id]
               AND [ep].[minor_id] = 0
               AND [ep].[class] = 1
               AND [ep].[name] = N'microsoft_database_tools_support'
      )
  )
  SELECT 1 ELSE SELECT 0

Beside that I am using this part of code:

var user = new User()
{
    UserName = "jaquine",
    PhoneNumber = "467-928-6562",
    FirstName = "Janine",
    LastName = "Quinevan"
};

var json = JsonConvert.SerializeObject(user);
var data = new StringContent(json, Encoding.UTF8, "application/json");
using var client = new HttpClient();
string url = Client.BaseAddress + RequestType.User;
var response = client.PostAsync(url, data).Result;

I tried to create similar empty project and it was working fine but in the main one it isn't and there is no errors.


Solution

  • As this document said:

    Beginning with .NET 6, new projects include the <Nullable>enable</Nullable> element in the project file. Once the feature is turned on, existing reference variable declarations become non-nullable reference types.

    In .NET 6 the non-nullable property must be required, otherwise the model validation will fail.

    To achieve your requirement, you can remove <Nullable>enable</Nullable> from your project file.