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
}
Repository.cs
:public async Task<IEnumerable<Todo>> GetTodosAsync() =>
await _context.Todos.ToListAsync();
Controller.cs
looks like below:public async Task<ActionResult<IEnumerable<Todo>>> GetTodosAsync() =>
Ok(await _repository.GetTodosAsync());
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With