I'm writing my first WEB-Api using ASP.NET Core. When I return items as JSON, there is such field as PhotoID which I don't wanna include in JSON-response. How can i realise it?
[HttpGet("{type}")]
public async Task<ActionResult> GetItems(int page, int count, string type)
{
var itemsCount = _context.ClothesItems.Where(i => i.Type == type).Count();
var amountToSkip = page == 1 ? 0 : page * count;
var amountToTake = count - amountToSkip;
if (amountToSkip >= itemsCount || count > amountToTake)
return BadRequest("The number of item need to take is out of range!");
var clothesItems = await _context.ClothesItems.Where(i=> i.Type==type)
.Include("Photos")
.Skip(amountToSkip)
.Take(amountToTake)
.ToListAsync();
var responsesStatusCode = Response.StatusCode;
var result = new
{
items = clothesItems,
total = itemsCount,
statusCode = responsesStatusCode,
};
return new JsonResult(result);
}
[1]: https://i.stack.imgur.com/I5wYq.jpg - json
CodePudding user response:
You can use the [JsonIgnore]
attribute in the photos model to prevent it from being de serialised. But this will also prevent this value from being captured from a request, if you are planning to use the same model as a request body.
Consider having a look at this for more information: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-5-0