Search code examples
c#azureazure-functionsjson-deserialization

How to return OkObjectResult without the extra stuff like Formatters?


When returning an OkObjectResult from my Azure Function like this:

    [Function("ReturnFoo")]
    public async Task<IActionResult> ReturnFoo([HttpTrigger(AuthorizationLevel.Anonymous, "post")]
        HttpRequestData req,
        FunctionContext executionContext)
    {
    object o = new
    {
        Foo = "bar"
    };

    return new OkObjectResult(o)
    }

It returns this JSON to the client:

 {
  "Value": {
    "Foo": "bar"
  },
  "Formatters": [],
  "ContentTypes": [],
  "DeclaredType": null,
  "StatusCode": 200
}

How can I return json that doesn't have all this extra stuff? I simply want:

 {
  "Value": {
    "Foo": "bar"
  }
}

Or, even better, just:

  {
    "Foo": "bar"
  }

I know I can change my return type of my Azure Function to 'object', but I really want to return an IActionResult so that I can return other messages from this same function easily.

I have wasted a bunch of time trying to get this to work with custom JSonFormatters, and trying with JsonResult (which also has bloated properties on it) and it's not working and I suspect I am missing something really obvious and simple. Appreciate the support.


Solution

  • For .NET 5+ with Isolated functions, you are intended to use HttpResponseData which is a far more procedural way to return data. https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide#bindings

    Hopefully API's will improve in the future.

    For a similar question, see: Using IActionResult with Azure Functions in .NET 5?