0

I have a .net core 3.1 API that returns customer information. In this return there is a password field. How do I stop the password field from returning with the customer object?

// 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;
        }

I tried using JsonIgnore but that won't let me POST seeing as my model has a required field for password.

[Required]
[JsonIgnore]
public string Password { get; set; }
TheDizzle
  • 1,534
  • 5
  • 33
  • 76

1 Answers1

2

Make a DTO which doesn't contain a field for the password, and then return the DTO instead:

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;
}
PajLe
  • 791
  • 1
  • 7
  • 21