I have this model
public class FooModel
{
public Guid ReferenceId { get; set; } // <-- this is the important part
public string SomeValue { get; set; }
}
And I have this controller endpoint
[HttpPost]
[ProducesResponseType(200)]
public async Task<IActionResult> SaveFoo([FromBody] FooModel model, CancellationToken ct)
{
await _fooManager.SaveFoo(model, ct);
return Ok();
}
My problem
If the client POSTS a json that looks like this with an invalid GUID for referenceId, The entire model
object received is null.
{
"referenceId": "some-invalid-guid!",
"someValue": "some valid value"
}
My desired outcome
I want the object that the endpoint receives to not be null, and contain the other values that were assigned. The referenceId
GUID would be either null or empty.
What I tried
I tried making the Guid nullable. Example: public Guid? ReferenceId { get; set; }
However this did not work. I imagine there is some de-serialization setting I need to change somewhere in my WebApi project, but I don’t know where.
2
Answers
I recommend declaring ReferenceId as a string instead of Guid. Then use
Guid.TryParse to validate ReferenceId after the post.
the only way to fix it is to use JsonElement as input parameter (or JObject if you use Newtonsoft.Json)
Newtonsoft