Search code examples
c#anonymous-class

How do I get dynamic properties from OkObjectResult


I return IActionResult with the value of an anonymous object from a controller method.
How do I get the data out again?

Here is the controller method reduced to the very problem:

[HttpPost]
public async Task<IActionResult> UploadFile(IFormFile file)
{
    long size = file.Length;
    return Ok(new { count = 1, size });
}

Then I get the .Value property, which is an object and make it dynamic.
But no, it is not recognised.

[Fact]
public async Task UploadFileTest()
{
    //  #   Given.
    var formFile = new Mock<IFormFile>();
    var sut = new HomeController(null);

    //  #   When.
    IActionResult result = await sut.UploadFile(formFile.Object);

    //  #   Then.
    OkObjectResult okResult = (OkObjectResult)result; // Ok.
    dynamic dynValue = okResult.Value; // Ok.
    var count = dynValue.count; // Not ok.
}

Expected result:

count should be 1.

Actual result:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'object' does not contain a definition for 'count'


Solution

  • Try reflection:

    var count = (int)okResult.Value.GetType().GetProperty("count").GetValue(okResult.Value);