简体   繁体   中英

REST API. Hide "password" field on response

I am very beginner at C#.Net Core. I use MongoDB to store some object. For explaining my problem, suppose, that I have two methods in "UserController": register and get. When I use regeister method, I send user object (something like that):

{
    id: 1,
    email: "test@test.com",
    name: "GoodUserName",
    password: "12345"
}

but when I use get-method, I want to hide password field, and I expect to get something like that (without password):

{
    id: 1,
    email: "test@test.com",
    name: "GoodUserName"
}

I try to use BsonIgnore,

Class User 
{
    ...
    [BsonIgnore]
    string password {get; set;}
    ...
}

but when I use register method there is empty password field. My problem is when I use my "get" controller, the "User" object in response include password field. Please, tell me best practise way to hide password on response.

the simple solution to your problem is to exclude the password property by using an exclusion projection when retrieving the user like this:

var projection = Builders<User>.Projection.Exclude(u => u.password);

var user = (await userCollection.FindAsync(
    filter: u => u.id == 1,
    options: new FindOptions<User, User> { Projection = projection })
    ).SingleOrDefaultAsync();

but... ideally you'd never wanna expose your data models/entities to your frontend like this. you should be using separate view models or DTOs and map between your domain entities on the way in as well as out. look up CQRS pattern for a good implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM