ASP.NET WebAPI Datashaper to Strip Your Json Data

May 30, 2015 reading time 4 minutes

ASP.NET WebAPI Datashaper to Strip Your Json Data

With this blog post I want to introduce you the ASP.NET WebAPI Datashaper to strip your json data before sending it back to the client.

The Datashaper gives you the possibility to strip the data you want to send based on the query of the client if you can not use Odata for a reason.

GitHub Project-Page NuGet

Demo

With this Nuget you can add the fields you want to receive in your request like:

GET /api/test?fields=Id,Title,Date

or

GET /api/test?fields=Id,Title,Date,ChildClasses.Description,ChildClasses.Id ...

You only have to call

Datashaper.CreateDataShapedObject(x, listOfFields)

in the end which is going to apply the list of Properties to your data.

This can be useful if you wnat to display a table of your data with only selected fields. You do not have to have every property from your model onto the client and display it. You only need specific fields which you can strip out with this package.

This is equivalent to the OData “$select”-Query option. But this package gives you the opportunity to get the same behaviour without using OData. But if you are interested you should take a look onto Odata, too.

Here is an example

[Route("myroute")]
public IHttpActionResult Get(string fields = null)
{
    try
    {
        //...

        List<string> listOfFields = new List<string>();
        if (fields != null)
        {
            listOfFields = fields.Split(',').ToList();
        }

        IQueryable<MyItems> myItems = _repository.GetMyItems();

        //...

        var result = myItems
            .ToList()
            .Select(x => Datashaper.CreateDataShapedObject(x, listOfFields));

        return Ok(result);
    }
    catch (Exception)
    {
         return InternalServerError();
    }
}

ASP.NET WebAPI Datashaper to strip your json data

ASP.NET WebAPI Datashaper to strip your json data

ASP.NET WebAPI Datashaper to strip your json data

ASP.NET WebAPI Datashaper to strip your json data

Regards & HTH

Fabian