I'm creating a WebAPI to do CRUD actions on entities. For my entities, in some endpoints, I don't return all of its properties for the sake of bandwidth and performance on my front end.
To achieve this I use a [JsonIgnore]
attribute on my Entity class, and when I want the entire class's info to be returned I use a custom ContractResolver
.
Here's an exemple of a class: (baseEntity simply has an id field)
public class Product : BaseEntity
{
public string Label { get; set; }
[JsonIgnore]
public string Color { get; set; }
public float Price { get; set; }
[JsonIgnore]
public string Description { get; set; }
}
and here's an example of the endpoint that causes me problems:
[Route("add")]
[HttpPost]
public IActionResult Add([FromBody] T paramEntity)
{
if (_entityService.Add(paramEntity))
{
return Content(convertObjectToJson(paramEntity), jsonContentType);
}
else
{
return StatusCode(500);
}
}
where T
is Product
The problem here is that the JsonIgnore
attributes are applied, so if I try to POST a request with values in Description
for instance, that field is totally ignored.
I found a workaround by making two Entity classes:
ProductParent
has noJsonIgnore
attributes and has all the initial properties ofProduct
;Product
still has them as seen above;Product
inherits fromProductParent
;ProductParent
is what is used as the parameter type for my POST request, as seen below, whereU
isProductParent
:
[Route("add")]
[HttpPost]
public IActionResult Add([FromBody] U paramEntity)
{
T entityToAdd = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(paramEntity));
var a = 1;
if (_entityService.Add(entityToAdd))
{
return Content(convertObjectToJson(entityToAdd), jsonContentType);
}
else
{
return StatusCode(500);
}
}
So while this kind of works it's unclean and could potentially stop working as soon as I move on to more complex types. Is there another way to achieve this?