I’m trying to make Json .NET Ignore a property by using the Json Ignore Attribute when clients GET the object but I want to be able to receive that property when a client is POST’ing
In example I have:
When the client POSTs data, password should be sent:
{"email":"email@domain.com","password":"P@ssW0rd1!","firstname":"Joe","lastname":"Doe"}
However, when the client GETs the same object, I should Ignore the Password:
{"email":"email@domain.com","firstname":"Joe","lastname":"Doe"}
Class:
public class User
{
public User()
{
this.JoinDate = DateTime.UtcNow;
this.IsActive = false;
}
public int Id { get; set; }
[Required(ErrorMessage = "Email is required!")]
public string Email { get; set; }
[JsonIgnore]
public string HashedPassword { get; set; }
[Required(ErrorMessage = "Password is required!")]
public string Password { get; set; }
public DateTime JoinDate { get; set; }
[Required(ErrorMessage = "First Name is required!")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is required!")]
public string LastName { get; set; }
}
Any ideas, suggestions, comments???
In your scenario here, I would recommend you to split your User class into 2 separate model classes:
This way, we are not depending on the serializer to hide sensitive data.
You could use [IgnoreDataMember] attributes and the out-of-box XML and JSON formatters will support them, but there is no guarantee that any other custom formatter registered will support it.
Note that [JsonIgnore] is only supported in the JSON formatter but not the XML formatter.