'ASP.NET Core 3.1 Web API: how to protect sensitive data from return with model?

I have a Posts model class that has a relation with Users model. When I call API to get Posts with the owner of it (user), it returns with all user info including password.

How to prevent model from returning sensitive information like passwords?



Solution 1:[1]

You should create new classes that you return from your actions. Only include the fields/information you want to return. These classes are also known as Data Transfer Objects (DTO).

Solution 2:[2]

You can use [JsonIgnore] to avoid serializing the property value:

public class Users 
{
    public int Id { get; set; }
    [System.Text.Json.Serialization.JsonIgnore]
    public string Password{ get; set; }
    //...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 keuleJ
Solution 2 Rena