0

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:

[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;
}
xHorizon
  • 35
  • 5

2 Answers2

2

You need to be more specific with return type:

[HttpGet]
public IActionResult<List<GetEndpointsDto>> GetAllEndpoints()
{
  ...
  return Ok(output.toList())
}
Eugene
  • 1,487
  • 10
  • 23
1

You should try public ActionResult<object> GetAllEndpoints() and then return something like return Ok(output) or also just return output I realized that I'm returning output in a API of mine and it works fine

Kvble
  • 286
  • 1
  • 8
  • Okay, so by returning just an object, how will the client then know if its json/xml or something else that it needs to accept? – xHorizon Apr 21 '22 at 13:44
  • 1
    It depends how you set your server not on what object you return, you can set the type of response you send to the client but that is another thing, your question is telling that you want to return different types of objects but the response format is a totally different thing from what you asked – Kvble Apr 21 '22 at 13:50