简体   繁体   English

如何访问Access json body/content (IActionResult)

[英]How to access Access json body/content (IActionResult)

I have an endpoint that calls another function that returns json object(IActionResult).我有一个调用另一个 function 的端点,它返回 json 对象 (IActionResult)。 How do I access the json data?如何访问 json 数据?

public async Task<IActionResult> GetData(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
             var empFunc = new employeeFunc(arg);

             var response = await empFunc.GetInfo(req,log);

        return response;

}

If I access the end point via postman.如果我通过 postman 访问终点。

{
    "message": "Found 2 records.",
    "entries": [
        {"id": "12345",
         "name":"Tony"
        },
        {"id": "123456",
         "name":"David"
        }
    ]

How do I access the json data in my C# code?如何访问我的 C# 代码中的 json 数据?

I tried something like following我尝试了类似以下的操作

var stream = await response.Content.ReadAsStreamAsync();
JObject object = JObject.Parse(readStreamToString(stream));

But errored out with following error但因以下错误而出错

Error   CS1061  'IActionResult' does not contain a definition for 'Content' and no accessible extension method 'Content' accepting a first argument of type 'IActionResult' could be found (are you missing a using directive or an assembly reference?)    

I also tried with我也试过

dynamic jsonResponse = JsonConvert.DeserializeObject<dynamic>(response);

and errors和错误

Error   CS1503  Argument 1: cannot convert from 'Microsoft.AspNetCore.Mvc.IActionResult' to 'string'

You can use HttpClient for API call in C# and access to the data:您可以使用HttpClient为 API 调用 C# 并访问数据:

HttpClient _httpClient = new HttpClient();
var response = await _httpClient.GetAsync("Your API URL");
response.EnsureSuccessStatusCode();
var jsonResult = await response.Content.ReadAsStringAsync();

Now, you have your JSON in jsonResult .现在,您的 JSON 在jsonResult中。 You can simply use Newtonsoft package to convert it to your own data type.您可以简单地使用Newtonsoft package 将其转换为您自己的数据类型。

var finalResult = JsonConvert.DeserializeObject<MyOutput>(jsonResult);

public class Entry
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class MyOutput
{
    public string Message { get; set; }
    public List<Entry> Entries { get; set; }
}

If you are calling the API directly, then you can use this:如果您直接拨打 API,那么您可以使用:

var controller = new YourController();
var okResult = await controller.GetInfo(req, log) as OkObjectResult;
var finalResult = okResult.Value as MyOutput;

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

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