jross
jross

Reputation: 59

How prevent some class properties from being returned from Web API?

I'm building a .NET Core Web API referencing a class library using Entity Framework Core. We're database-first so will foreseeable be overwriting our data classes periodically to refresh them.

For e.g. an Employee object that has FirstName, LastName, but also Password, how can I prevent the Password attribute from being passed back with the object?

If I need to manipulate the data class, will I have to remember to manually re-edit every time I delete/re-create my data classes? Thank you for any help!

Upvotes: 1

Views: 461

Answers (1)

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

You should use Data Transfer Objects (DTOs). Populate custom properties using a mapper and send it to the response. Also you can try this (Anonymous Types):

var employee = ...get from db;

return Ok(new
{
    employee.FirstName,
    employee.LastName
});

Upvotes: 1

Related Questions