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;
}
CodePudding user response:
You need to be more specific with return type:
[HttpGet]
public IActionResult<List<GetEndpointsDto>> GetAllEndpoints()
{
...
return Ok(output.toList())
}
CodePudding user response:
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