Home > Blockchain >  C# Task<IActionResult> Return Json
C# Task<IActionResult> Return Json

Time:08-19

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:

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.

---- EDIT ----

I have update based on feedback from @blindy which has unescaped the response data but is still wrapping as shown:

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

I Assume this is due to the Task? if so is there a best practice way to return just the data as a JSON object using the return public static Task<IActionResult> Run

CodePudding user response:

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).

CodePudding user response:

You don't need to serialize an object to json, Net will do it for you.

return Ok(testdata);
  • Related