ehftwelve
ehftwelve

Reputation: 3137

MongoDB C# - Hide property from serializer

This is what my user model looks like:

namespace Api.Models
{
    public class User
    {

        [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
        [BsonRequired]
        public string Id { get; set; }

        [Required(ErrorMessage = "Username is required.")]
        [StringLength(20, MinimumLength=3, ErrorMessage="Username must be between 3 and 20 characters.")]
        [BsonRequired]
        public string Username { get; set; }

        [Required(ErrorMessage="Email is required.")]
        [EmailAddress(ErrorMessage="Valid email required.")]
        [BsonRequired]
        public string Email { get; set; }

        [Required(ErrorMessage = "Password is required.")]
        [StringLength(50, MinimumLength=8, ErrorMessage="Password must be between 8 and 50 characters.")]
        [BsonRequired]
        public string Password { get; set; }

        [BsonRequired]
        public string Salt { get; set; }

    }
}

I want to write, and require, all of the properties into the MongoDB Database. What I don't want to do, is expose the Password and Salt properties when I send this through the request.

Is there any sort of data attribute that I can set that will write it, but not expose it when displayed to any API user?

Upvotes: 1

Views: 895

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039130

The correct approach is to use view models. Don't pass your domain entities to the views. Design view models that meet the specific requirements of your views. So for example design a view model that doesn't have the Password and Salt properties because that's what this view needs. Then in order to ease the mapping between your domain models and view models you could use AutoMapper.

If you don't want to follow good practices with view models you still have the possibility to clutter your POST actions with the Bind attribute and decide which properties you want to be included/excluded from model binding. For example:

[HttpPost]
public ActionResult SomeAction([Bind(Exclude="Password,Salt")]User user)
{
    // at this stage the Password and Salt properties will always be null =>
    // they will never be bound from the request even if the user attempts to 
    // forge an HTTP request and include them
    ...
}

Upvotes: 2

Related Questions