简体   繁体   English

C# 任务<iactionresult>返回 Json</iactionresult>

[英]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: 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: 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: Function App 入口点和返回码:

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:测试 Worker Class 用于返回的 object 数据和 JSON 序列化:

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.我已经尝试了几种方法来尝试使用响应 object 类型来达到一个干净的 JSON output 类型,因为最好添加基于 ObjectResults 的逻辑,但我错过了明显的怀疑线,

If the return is set to: return Task.FromResult(results);如果返回设置为: return Task.FromResult(results); the the response is an escaped JSON output:响应是转义的 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));如果返回修改为: return Task.FromResult<IActionResult>(new OkObjectResult(results)); then the response is escaped but encapsulated in a Object wrapper:然后响应被转义但封装在 Object 包装器中:

{
    "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:我想要实现的只是将正确的响应 header 作为 application/json 和结果集如下所示:

{
  "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).您想返回new JsonResult(data) ,其中data是您的托管结构(不是像您出于某种奇怪的原因那样序列化的 json 数据)。

You don't need to serialize an object to json, Net will do it for you.您不需要将 object 序列化为 json,Net 会为您完成。

return Ok(testdata);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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