Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

FromBody does not ignore properties decorated with JsonIgnore on POST

I’m building a controller that should recerive a Workflow type via the request’s body, but it doesn’t respect the JsonIgore attribute and throws a model validation error that says:

"The Name field is required."

When I look into what body Swagger suggests then it’s what one would expect:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
  "schedule": "string",
}

But even when I explicitly specify name in my request, it still does throw the same exception. Why?


This is my test setup:

public class Workflow
{
    [JsonIgnore]
    public string Name { get; set; }

    public string Schedule { get; set; }

    // ...
}

[ApiController]
[Route("api/[controller]")]
public class WorkflowsController : ControllerBase
{    

    [HttpPut("{workflowName}")]
    public async Task<int> CreateWorkflow(string workflowName, [FromBody] Workflow workflow)
    {
        return await Task.FromResult(0);
    }
}

Do I have to create another class for the body or is there a way to fix that strange behavior?

>Solution :

JsonIgnore will just ignore that property for serialisation, meaning it won’t set it. Since you’re using nullable reference types, the property Name is expected to have a value & model validation will take this into account.

You can either give it a default value

public string Name { get; set; } = string.Empty;

Or make it nullable

public string? Name { get; set; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading