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

8.1k Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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

0
On

I think this might help someone, it's related to Felipe Augusto answer.


If you use WriteAsJsonAsync() you must not add the header Content-Type manually:

response.Headers.Add("Content-Type", "application/json; charset=utf-8");

That's because WriteAsJsonAsync() already does that, as stated in the documentation:

Write the specified value as JSON to the response body.
The response content-type will be set to application/json; charset=utf-8.

If you try adding the header, you'll get a k8s.Autorest.HttpOperationException:

Error: Cannot add value because header 'Content-Type' does not support multiple values.
0
On

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;