How do I return JSON only from Azure Functions (dotnet5)

Viewed 2399

I have a set of HttpTrigger Azure Functions in dotnet5 and I want to return JSON from those Azure Functions. I'm using return new OkObjectResult(myObject) but that is not providing JSON but rather the JSON is in the "Value" element of the JSON returned i.e. the results look a bit like

{
  "Value": {
    "MyValueOne": true,
    "MyValueTwo": 8
  },
  "Formatters": [],
  "ContentTypes": [],
  "DeclaredType": null,
  "StatusCode": 200
}

as opposed to the expected

{
    "MyValueOne": true,
    "MyValueTwo": 8
}

I've gone down a couple paths with different return objects, but they always seem to be having these extra values and the JSON I want returned usually wrapped up in a Value or Content with in other JSON, for example: JsonResult(myObject) OR ContentResult() { Content = serialisedVersionOfMyObject }

I even tried the HttpResponseMessage path; but ran into trouble with the HttpTrigger and expected return of Tast

I feel like I'm missing something simple; what is the expected / desired / straight-forward way of returning "just json" from an Azure Function?

2 Answers

if you need to return a object (serialized), try to do this:

you will have one parameter in you Azure Function, the type and name are (HttpRequestData req), now you need to use this to create you response:

var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteAsJsonAsync(itemData); <-- itemData = your object

return response;

Azure function .net 5 returns the HttpResponseData as output of Http trigger function. More info here.

Text from the documentation:

HTTP triggers translates the incoming HTTP request message into an HttpRequestData object that is passed to the function. This object provides data from the request, including Headers, Cookies, Identities, URL, and optional a message Body. This object is a representation of the HTTP request object and not the request itself.

Likewise, the function returns an HttpResponseData object, which provides data used to create the HTTP response, including message StatusCode, Headers, and optionally a message Body.

enter image description here

Related