Thursday, February 5, 2015

WebAPI OData v4: Cannot serialize a null 'entry'

In that kind of function:

public IHttpActionResult MyFunction([FromODataUri]int myParameter)
{
 return Ok(GetFoo(myParameter));
}

This may lead to the error 500 described in the title if the returned value is null. Based on this thread, One way would be to return an empty response when the return value is null:

public IHttpActionResult MyFunction([FromODataUri]int myParameter)
{
 var retval = GetFoo(myParameter);
 if (retval != null)
  return Ok(retval);
 else
  return Ok();
}

The result is a 202 OK empty response, but this doesn't seem to please some OData frameworks as I sometimes get a "Unexpected server response" message on the client side.

Now, based on this other thread, it seems the clean way to do this is to return a 404 error when the return value is null and act accordingly on the client side:

public IHttpActionResult MyFunction([FromODataUri]int myParameter)
{
 var retval = GetFoo(myParameter);
 if (retval != null)
  return Ok(retval);
 else
  return NotFound();
}


No comments: