简体   繁体   English

在C#代码中隐藏属性

[英]Hide a property in c# code

I have a Business class say User.cs: 我有一个业务类说User.cs:

  [Serializable]
    public class User
    {

        public int UserID { get; set; }
        public string UserName { get; set; }
        public int Password { get; set; }

    }

In my server side code I am writing the following code to serialize the user object in JSON format: 在服务器端代码中,我正在编写以下代码以JSON格式序列化用户对象:

User user=SomeUserBLClass.GetUser(1);
Response.Write(new JavaScriptSerializer().Serialize(user));

My requirement is to hide the password being sent to client side ie I don't want the password field to come in json data. 我的要求是隐藏发送到客户端的密码,即我不希望密码字段包含在json数据中。 Can you help me fixing this? 你能帮我解决这个问题吗?

You could add the [ScriptIgnore] attribute to Password . 您可以将[ScriptIgnore]属性添加到Password

[Serializable]
public class User
{

    public int UserID { get; set; }
    public string UserName { get; set; }

    [ScriptIgnore]
    public int Password {get; set;}
}

如何使用匿名类型和省略密码?

Response.Write(new JavaScriptSerializer().Serialize(new {UserId = user.UserId, UserName = user.UserName});

Exclude the Password field entirely from the user object, and only allow internal usage of the backend version within SomeUserBLClass via methods such as ValidateUser or ChangePassword. 完全从用户对象中排除“密码”字段,并且仅允许通过ValidateUser或ChangePassword之类的方法在SomeUserBLClass中内部使用后端版本。

You don't really want any version of the password exposed to the front layer in any form - there is always the chance that the display layer throws a wobbly and dumps data to the client in some form. 您实际上并不希望以任何形式将任何版本的密码公开给顶层-显示层始终有机会以某种形式摆动并向客户端转储数据。

Remove it from the equation, and only allow transitional access to it, and it ceases being an issue. 从等式中删除它,只允许对其进行过渡访问,这不再是一个问题。

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

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