Returning Json response from Azure Function v3+

It can be a pain to return json-responses from a Function App, when you also want the proper Content-Type HTTP header to be returned, which it of course should.

If you do it the straight-forward way (works the same with OkObjectResult) –

return new BadRequestObjectResult(jsonResponse);

if response contains a json string, it will be returned ok, but the Content-Type will be “text/plain”

BadRequestObjectResult resp = new BadRequestObjectResult(jsonResponse);
resp.ContentTypes.Add(MediaTypeHeaderValue.Parse("application/json"));
resp.Value = jsonResponse;
return resp;

if response contains a json string, the special characters (like “) will be escaped, and it will no longer return valid json, but the Content-Type is ok (application/json)

If the content-type is not set in above example, the special characters are not escaped

If you return a JsonResult as suggested in some places, the ContentType will be correct, but the Json will be escaped.

return new JsonResult(jsonResponse);

Make a class like this

using System.Text.Json;
using Microsoft.AspNetCore.Mvc;

namespace Azure.Function.Returning.Json.Response {
  public class CustomJsonResult : ContentResult {
    private const string ContentTypeApplicationJson = "application/json";

    public CustomJsonResult(object p_value, JsonSerializerOptions p_options = null, int p_statusCode = 200) {
      ContentType = ContentTypeApplicationJson;
      Content = p_options == null ? JsonSerializer.Serialize(p_value) : JsonSerializer.Serialize(p_value, p_options);
      StatusCode = p_statusCode;
    }
  }
}

and return response like

 return new CustomJsonResult(jsonResponse, new JsonSerializerOptions { PropertyNamingPolicy = null }, 400);

This way, correct json will be returned as well as correct Content-Type