gpt4 book ai didi

c# - 如何访问Access json正文/内容(IActionResult)

转载 作者:行者123 更新时间:2023-12-03 06:47:06 24 4
gpt4 key购买 nike

我有一个端点,它调用另一个返回 json 对象 (IActionResult) 的函数。如何访问 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;

}

如果我通过 postman 访问端点。

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

如何在 C# 代码中访问 json 数据?

我尝试了类似以下内容

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

但出现以下错误

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

我也尝试过

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

和错误

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

最佳答案

您可以使用HttpClient在C#中进行API调用并访问数据:

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

现在,您的 JSON 已位于 jsonResult 中。您只需使用 Newtonsoft 包将其转换为您自己的数据类型。

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; }
}

如果您直接调用 API,则可以使用:

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

关于c# - 如何访问Access json正文/内容(IActionResult),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74010498/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com