Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to return anonymous object through an IActionResult Endpoint

I have a problem when I try to return an anonymous object/DTO from an endpoint in my ASP .NET Core 6 Web-Api Project. I get an error that it cannot implicitly convert the type to an IActionResult. The code I use was suggested in this answer but unfortunately it doesn’t work out for me, I also tried using to map the anonymous object to an dto but that didn’t work either. Any help would be greatly appreciated, thanks in advance.

I also tried to return an Json(output) like suggested in the answer but, Json() I can’t specify a using for “Json”, I also tried to return an JsonResult(output) by modifying the return type of the endpoint but that didn’t work either.

This is the code I use:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[HttpGet]
public IActionResult GetAllEndpoints()
{
    var endpoints = _endpoinDataSources
    .SelectMany(es => es.Endpoints)
    .OfType<RouteEndpoint>();
    var output = endpoints.Select(
        e =>
        {
            var controller = e.Metadata
                .OfType<ControllerActionDescriptor>()
                .FirstOrDefault();
            var action = controller != null
                ? $"{controller.ControllerName}.{controller.ActionName}"
                : null;
            var controllerMethod = controller != null
                ? $"{controller.ControllerTypeInfo.FullName}:{controller.MethodInfo.Name}"
                : null;
            return new GetEndpointsDto
            {
                Method = e.Metadata.OfType<HttpMethodMetadata>().FirstOrDefault()?.HttpMethods?[0],
                Route = $"/{e.RoutePattern.RawText.TrimStart('/')}",
                Action = action,
                ControllerMethod = controllerMethod
            };
        }
    );

    return output;
}

I also injected the EndPointDataSource through the controller constructor:

public MyController(IEnumerable<EndpointDataSource> endpointSources)
{
    _endpoinDataSources = endpointSources;
}

>Solution :

You need to be more specific with return type:

[HttpGet]
public IActionResult<List<GetEndpointsDto>> GetAllEndpoints()
{
  ...
  return Ok(output.toList())
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading