Search code examples
asp.netodataasp.net-web-api2

What should I return when my oData V4 method returns SingleResult<T> and nothing is found?


I have a controller method in an oData V4 project that returns SingleResult. It queries a table that, when it has data in it, returns what it should. However when the app is new and the table is empty it gives a nondescript error:

"'SingleResult`1' cannot be serialized using the ODataMediaTypeFormatter."

My method looks something like the following:

    [EnableQuery]
    public virtual SingleResult<LoggerEntry> Get([FromODataUri] int key)
    {
        using (var gateway = this.Gateway.GetChild())
        {
            var model = gateway.GetLoggerEntry(key);
            // TODO: Check for null and tell the client NotFound
            return SingleResult.Create((new List<LoggerEntry>(){ model }).AsQueryable());
        }
    }

Because I am using SingleResult I am not able to just return NotFound();. I have tried to use an empty list but that gives me the same error. I can not find an example or documentation for what to return in this case. What should I be returning.


Solution

  • keep your original code and try use ODataNullValueMessageHandler

            configuration.MapODataServiceRoute(
                "odata", 
                "odata", 
                GetEdmModel(configuration),
                defaultHandler: HttpClientFactory.CreatePipeline(innerHandler: new HttpControllerDispatcher(configuration), handlers: new[] { new ODataNullValueMessageHandler()}));