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:
{
"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; }