'How can I change an endpoint that returns one object to be filterable on which properties to return?
I want to find the cleanest way to do this but haven't had much luck on google. I'm returning an Information object that has properties assemblies, configuration, and cassandra.
I want it to work so if I call /api/Information?filter=Assemblies,Configuration, it returns only the assemblies and configuration properties, leaving out cassandra.
I can do this currently but I'm doing it with if else statements. Is there a better approach to this, maybe with an interface?
Solution 1:[1]
I think what you are looking for that would work for .net very well is OData.
Solution 2:[2]
You can use odata to do that it is exactly what you need.
Startup.cs should be modified like this.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<yourDbContext>(opt => opt.UseInMemoryDatabase("yourList"));
services.AddControllers().AddOData(opt => opt.AddRouteComponents("api", GetEdmModel())
.Filter().Select());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Send "~/$odata" to debug routing if enable the following middleware
// app.UseODataRouteDebug();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
private static IEdmModel GetEdmModel()
{
// …
}
}
Controller should be like this:
public class InformationController : ControllerBase
{
[HttpGet]
[EnableQuery]
public IEnumerable<Information> Get()
{
//…your logic
}
}
Api
So if you do /api/Information?Select=Assemblies,Configuration you will only get assemblies and configuration.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | merlinabarzda |
| Solution 2 | Abhinn Mishra |
