简体   繁体   中英

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:

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.

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

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

return Ok(testdata);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM