Get a Value from ActionResult<object> in a ASP.Net Core API Method
Asked Answered
E

3

33

I try to get a value from ActionResult<object> in an ASP.NET Core API method.

The API has a different controller. I try to use a method from controller B in controller A to return the result value. I get an ActionResult object from controller B. I can see the value with the debugger in the ResultObject but how can I get access to the result value in it?

public ActionResult<object> getSourceRowCounter(string sourcePath) //Method from Controller A
{
    var result = ControllerB.GetValue($"{sourcePath}.{rowCounterVariableName}");  
    var result2 = result.Value; //null
    var result3 = result.Result; //typ: {Microsoft.AspNetCore.Mvc.OkObjectResult} <-see Value=4 in it with Debugger
    //var result4 = result3.Value; //Error?!
    //var result5 = result3.Content; //Error?!
    //var result6 = result3.?????; //How can i get the Value = 4?
    return Ok(result); //should only return value 4 and not the whole object
}

enter image description here

Excursion answered 27/4, 2020 at 7:38 Comment(1)
Does this answer your question? How to Unit Test with ActionResult<T>?Dextrad
B
34

If you're sure that it is a type of OkObjectResult then cast before using it like below:

var result3 = (OkObjectResult)result.Result; // <-- Cast is before using it.
var result4 = result3.Value; //<-- Then you'll get no error here.
Breann answered 27/4, 2020 at 7:43 Comment(3)
How to handle this when instead of OkObjectResult, we have 4 different types, can we do this without cast?Houk
You can also just cast to ObjectResult and still get Value, which can handle multiple result types, eg OkObjectResult, UnauthorizedObjectResult, etc.Giraud
In my case I had to cast it to JsonResult to get it to work.Urogenous
A
25
Suppose you have example function in Repository.cs:
public async Task<IEnumerable<Todo>> GetTodosAsync() =>
   await _context.Todos.ToListAsync();
And function in Controller.cs looks like below:
public async Task<ActionResult<IEnumerable<Todo>>> GetTodosAsync() =>
    Ok(await _repository.GetTodosAsync());
Then in your UnitTest.cs you can get results by doing this:
var result = await controller.GetTodosAsync();
// list of todos is in `actual` variable
var actual = (result.Result as OkObjectResult).Value as IEnumerable<Todo>;
// or use `ObjectResult` instead of `OkObjectResult` for multiple types
Andria answered 18/7, 2021 at 21:55 Comment(1)
Underrated comment!Ivanna
P
0

If you are calling an API from action and the API returns Ok(result) which you want to access in your action then below code can help you:

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{                                   
    return Ok(response.Content); // returns API result
}
Posterity answered 4/5, 2021 at 10:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.