我有一个.net core 3.1 API,可返回客户信息。在此返回中,有一个密码字段。如何阻止密码字段与客户对象一起返回?
// GET api/<CustomersController>/5
[HttpGet("{id}")]
public async Task<ActionResult<Customer>> Get(Guid id)
{
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{
return NotFound();
}
return customer;
}
我尝试使用JsonIgnore
,但由于我的模型具有必填的密码字段,因此我无法开机自检。
[Required]
[JsonIgnore]
public string Password { get; set; }
答案 0 :(得分:2)
制作一个DTO,其中不包含密码字段,然后返回DTO:
public class CustomerDTO
{
// Customer's fields without the password
}
[HttpGet("{id}")]
public async Task<ActionResult<CustomerDTO>> Get(Guid id)
{
var customer = await _context.Customers.FindAsync(id);
if (customer == null)
{
return NotFound();
}
var customerToReturn = MapCustomerToCustomerDTO(customer); // manually do this, or use some auto mapper
return customerToReturn;
}