/DataFilters.AspNetCore

Primary LanguageC#Apache License 2.0Apache-2.0

GitHub Main branch Status GitHub Workflow Status (develop) codecov GitHub raw issues Nuget

DataFilters.AspNetCore

A small library that ease usage of DataFilters with ASP.NET Core APIs.

Why

Make it easier to build IFilter instances

DataFilters allows to build complex queries in a "restfull" way. However, it comes with some drawbacks.

In order to build a filter, you have to :

  1. parse the incoming string
  2. map it manually to an underlying model type.
  3. converts it into an IFilter instance using the .ToFilter<T> extension method.

This can be a tedious task and this library can help to ease that process.

Reduce the bandwith usage

The library can help reduce bandwith usage. This can be done in two differnet ways :

  • using x-datafilters-fields-include / x-datafilters-fields-exclude custom HTTP headers
  • using [Prefer] HTTP header, .

Custom HTTP headers

x-datafilters-fields-include

x-datafilters-fields-include custom HTTP header allows to specified which properties that will be kept in the body response.

x-datafilters-fields-exclude

x-datafilters-fields-exclude custom HTTP header allows to specify which properties that will be dropped from the body response.

These custom headers can be handy for mobile clients that query a REST API by reducing the volume of data transfered from backend. This can also allow to design one API that can serve multiple clients : each client could "select" the properties it want to display.

Prefer HTTP header support

This library offers a limited support of the Prefer HTTP header. Specifically, a client can request a "minimal" representation of the resource by setting the Prefer: return=minimal HTTP header.

Given the following request

GET /api/users HTTP/1.1

Prefer: return=minimal

and the following C# class where the MinimalAttribute is applied to both Name and Id properties :

public class Person
{
    [Minimal]
    public Guid Id { get; set; }
    [Minimal]
    public string Name { get; set; }
    public string Email { get; set; }
}

the server can respond with a "minimal" representation of the resource.

HTTP/1.1 200 OK

<headers omitted for brevity>

[
   {
       "id": "83c39be2-5123-47bf-a1d1-9df15d146e6a",
       "name": "John Doe"
   },
   {
       "id": 2,
       "name": "Jane Doe"
   }
]

To enable support of the Prefer: return=minimal HTTP header :

  1. Register an instance of PreferActionFilterAttribute in your filters
services.Filters.Add(new PreferActionFilterAttribute());
  1. Annotate properties in your classes with MinimalAttribute.

Improve performances

The library comes with an implementation of IDataFilterService that can be used to build IFilter instances: each instance will be cached and reused when needed.

How to install

  1. Simply run dotnet install DataFilters.AspNetCore to add the package to your solution
  2. You're ready to go