Home > Mobile >  How to require a json key to be present but allow the value to be null
How to require a json key to be present but allow the value to be null

Time:03-27

I have a model with a nullable double in my API, I want anyone posting to it to be required to include the key in the json body. I am using the [FromBody] to receive the data from the json in the post function.

Any ideas if this is even possible?

CodePudding user response:

Annotate it with the required attribute https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-6.0#non-nullable-reference-types-and-required-attribute

or do a check in the controller for the property and if it’s null return BadRequest

CodePudding user response:

Solved it be installing the NewtonsoftJson package with the nuget package manager then adding this line to the ConfigureServices:

services.AddMvc().AddNewtonsoftJson();

And adding the following attribute to the property in the model

[JsonProperty(Required = Required.AllowNull]
  • Related