我正在使用 ASP.NET Core 编写我的第一个 WEB-Api。当我以 JSON 形式返回项目时,有一个诸如
PhotoID
之类的字段,我不想将其包含在 JSON 响应中。我怎样才能实现它?
[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);
}
您可以在照片模型中使用
[JsonIgnore]
属性来防止其被反序列化。但是,如果您计划使用相同的模型作为请求正文,这也会阻止从请求中捕获该值。
考虑查看此内容以获取更多信息:https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-ignore-properties?pivots=dotnet-5-0