TheDizzle
TheDizzle

Reputation: 1574

Remove Property from Returned object in c#

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

Upvotes: 0

Views: 1470

Answers (1)

PajLe
PajLe

Reputation: 924

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

Upvotes: 2

Related Questions