skip to Main Content

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


  1. I recommend declaring ReferenceId as a string instead of Guid. Then use
    Guid.TryParse to validate ReferenceId after the post.

    Login or Signup to reply.
  2. the only way to fix it is to use JsonElement as input parameter (or JObject if you use Newtonsoft.Json)

    [HttpPost]
     public async Task<IActionResult> SaveFoo([FromBody] JsonElement element, CancellationToken ct)
    {
        string referenceId = element.GetProperty("ReferenceId").GetString();
    
        if(Guid.TryParse(referenceId, out var referenceGuid))
       {
         FooModel model = element.Deserialize<FooModel>();
          //... your code
       }
         
    }
    

    Newtonsoft

    [HttpPost]
     public async Task<IActionResult> SaveFoo([FromBody] JsonObject obj, CancellationToken ct)
    {
       string referenceId = (string) obj["ReferenceId"];
    
        if(Guid.TryParse(referenceId, out var referenceGuid))
       {
         FooModel model = jObj.ToObject<FooModel>();
          //... your code
       }
         
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search