简体   繁体   English

REST API。 在响应中隐藏“密码”字段

[英]REST API. Hide "password" field on response

I am very beginner at C#.Net Core.我是 C#.Net Core 的初学者。 I use MongoDB to store some object.我使用 MongoDB 来存储一些 object。 For explaining my problem, suppose, that I have two methods in "UserController": register and get.为了解释我的问题,假设我在“UserController”中有两种方法:注册和获取。 When I use regeister method, I send user object (something like that):当我使用注册方法时,我发送用户 object (类似的东西):

{
    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):但是当我使用get方法时,我想隐藏密码字段,我希望得到类似的东西(没有密码):

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

I try to use BsonIgnore,我尝试使用 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.我的问题是当我使用我的“get”controller 时,“用户”object 响应包含密码字段。 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.您应该在进出的域实体之间使用单独的视图模型或 DTO 和 map。 look up CQRS pattern for a good implementation.查找 CQRS 模式以获得良好的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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