3

I have a Business class say 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:

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

My requirement is to hide the password being sent to client side i.e I don't want the password field to come in json data. Can you help me fixing this?

2
  • Is password really an int? o_O Commented Nov 17, 2011 at 15:17
  • No :) just for a sample code. Commented Nov 17, 2011 at 16:48

3 Answers 3

7

You could add the [ScriptIgnore] attribute to Password.

[Serializable]
public class User
{

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

    [ScriptIgnore]
    public int Password {get; set;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't [ScriptIgnore] achieve the same, but work on an auto property?
@David: Absoutely it would, I hadn't come across [ScriptIgnore] before, thanks. I'll change the answer so.
3

How about using an anonymous type and omitting password?

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

1 Comment

I like this solution because it forces you to think about what you really need to pass on to the client. Otherwise you'll soon enough end up in a situation where you're hiding the password, because you cared about that, but you still serialize heaps of fields that weren't really necessary.
0

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.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.