1

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.

  • You can create your own class that implements `IActionResult` and return that – stuartd Dec 10 '22 at 16:24
  • @stuartd I have tried, but I cant find any docs online of how to do the custom serilization? Can you point me to any? – user3010678 Dec 10 '22 at 16:37
  • @stuartd I am using .NET 7/Isolated. – user3010678 Dec 10 '22 at 16:43
  • Seen this https://stackoverflow.com/questions/38943858/how-do-i-return-json-from-an-azure-function ? – Anand Sowmithiran Dec 11 '22 at 09:27
  • Does this answer your question? [How do I return JSON from an Azure Function](https://stackoverflow.com/questions/38943858/how-do-i-return-json-from-an-azure-function) – Anand Sowmithiran Dec 11 '22 at 09:28
  • @AnandSowmithiran, thanks for sharing. Does this mean its not possible to do this with IAsyncResult, and I need to use HttpResponseMessage? – user3010678 Dec 11 '22 at 15:56
  • Please edit your question to indicate the use of Isolated function. That's still a fairly new hosting model and answers are likely to be geared toward in-process if not specified. – DannyMeister Feb 22 '23 at 22:17
  • Does this answer your question? [Using IActionResult with Azure Functions in .NET 5?](https://stackoverflow.com/questions/67045378/using-iactionresult-with-azure-functions-in-net-5) – DannyMeister Feb 22 '23 at 22:21

1 Answers1

2

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?

DannyMeister
  • 1,281
  • 1
  • 12
  • 21