I have an endpoint that calls another function that returns json object(IActionResult). How do I access the json data?
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.
{
"message": "Found 2 records.",
"entries": [
{"id": "12345",
"name":"Tony"
},
{"id": "123456",
"name":"David"
}
]
How do I access the json data in my C# code?
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 _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
. You can simply use Newtonsoft
package to convert it to your own data type.
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:
var controller = new YourController();
var okResult = await controller.GetInfo(req, log) as OkObjectResult;
var finalResult = okResult.Value as MyOutput;
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.