C
C#10mo ago
Vortac

✅ ASP Net 7 - Return list of objects as an object with a nested list

I have an endpoint with the following code:
public async Task<List<Page>> ListPages()
{
var pages = await _dbContext.Pages.ToListAsync();

return pages;
}
public async Task<List<Page>> ListPages()
{
var pages = await _dbContext.Pages.ToListAsync();

return pages;
}
This returns a list like:
[
{
"id": 1,
"title": "Hello ASP!",
"body": "<p>Testing</p>",
"author": "M"
},
{
"id": 2,
"title": "Second Page",
"body": "<p>Cool!</p>",
"author": "M"
}
]
[
{
"id": 1,
"title": "Hello ASP!",
"body": "<p>Testing</p>",
"author": "M"
},
{
"id": 2,
"title": "Second Page",
"body": "<p>Cool!</p>",
"author": "M"
}
]
I want to return:
```
{ "data":
[{
"id": 1,
"title": "Hello ASP!",
"body": "<p>Testing</p>",
"author": "M"
},
{
"id": 2,
"title": "Second Page",
"body": "<p>Cool!</p>",
"author": "M"
}]
}
```
{ "data":
[{
"id": 1,
"title": "Hello ASP!",
"body": "<p>Testing</p>",
"author": "M"
},
{
"id": 2,
"title": "Second Page",
"body": "<p>Cool!</p>",
"author": "M"
}]
}
```
5 Replies
unhAPI
unhAPI10mo ago
so put your List<Page> in an object 🤷 also can you consider not returning your raw db object from a controller? there are probably fields in there that shouldn't be given to the world to see instead you could build a model specifically for this need
Unknown User
Unknown User10mo ago
Message Not Public
Sign In & Join Server To View
Vortac
Vortac10mo ago
There's no fields in the DB object that need to be kept hidden:
public class Page
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string? Title { get; set; }
public string? Body { get; set; }
public string? Author { get; set; }
}
public class Page
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string? Title { get; set; }
public string? Body { get; set; }
public string? Author { get; set; }
}
but I assume there should be a second class called PageDto to send to the client?
unhAPI
unhAPI10mo ago
There's no fields in the DB object that need to be kept hidden:
we could argue about Id but anyway the dto could have some specific attributes for serialization, for example also it could be a specific dto for a feature instead of the whole thing, which could help keep stuff organized (say you event only want a dto for creating and one for retrieving the model)
Vortac
Vortac10mo ago
I have an endpoint called /api/pages/{id} where users can pass a pageId to get that specific page, but I can see why it would be hidden in other cases
Want results from more Discord servers?
Add your server