Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Task<IActionResult> Return Json

I am writing my first Azure FunctionApp, and I am looking to return a valid JSON Object from a deserialized class that was created from a Faker JSON object as shown below:

Class:

public class TestData
{
    //based on faker API 
    public int userId { get; set; }
    public int id { get; set; }
    public string title { get; set; }
    public bool completed { get; set; }
}

Function App Entry point and return code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public static Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,ExecutionContext context, ILogger log)
{
    var configBuilder = new ConfigurationBuilder()
        .SetBasePath(context.FunctionAppDirectory)
        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables();

    var config = configBuilder.Build();
    log.LogInformation("Config Loaded");

    // for later use when i get past the current issue
    var settings = new AppSettings();
    config.Bind("AppSettings", settings);
    
    //Setting this seems to be the route cause, but need to respond correctly?
    req.HttpContext.Response.Headers.Add("Content-Type", "application/json");
    var worker = new WorkerClass();
    var results = worker.DoSomeWork();
    return Task.FromResult(results);
    //Also Tried:
    //return Task.FromResult<IActionResult>(new OkObjectResult(results));
}

Test Worker Class for returned object data and JSON Serialization:

public class WorkerClass
{
   public IActionResult DoSomeWork()
    {
        try
        {
            var testdata = new TestData
            {
                userId = 123,
                id = 1,
                title = "delectus aut autem",
                completed = true
            };
            //formatted as Json correctly
            var results = JsonConvert.SerializeObject(testdata, Formatting.Indented);
            return new OkObjectResult(results);
        }
        catch (Exception dswEx)
        {
            return new BadRequestObjectResult($"\{ERROR: {dswEx.Message}\}");
        }
    } 
}

I have tried several ways to try and reach a clean JSON output using the response object types, as it would be good to add logic based on ObjectResults further down the line, but I suspect I am missing the obvious.

If the return is set to: return Task.FromResult(results); the the response is an escaped JSON output:

"{\"userId\": 1,\"id\": 1,\"title\": \"delectus aut autem\",\"completed\": false}"

if the return is amended to be: return Task.FromResult<IActionResult>(new OkObjectResult(results)); then the response is escaped but encapsulated in a Object wrapper:

{
    "value": "{\r\n \"userId\": 1,\"id\": 1,\"title\": \"delectus aut autem\",\"completed\": false}",
    "formatters": [],
    "contentTypes": [],
    "declaredType": null,
    "statusCode": 200
}

All I would like to achieve is to have the correct response header as application/json and a result set presented as follows:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Thanks in advance.

>Solution :

You want to return new JsonResult(data), where data is your managed structures (not serialized json data like you were doing for some odd reason).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading