1

これは私のユーザーモデルがどのように見えるかです:

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; }

    }
}

すべてのプロパティをMongoDBデータベースに書き込み、要求したいと思います。私がやりたくないのは、リクエストを介してこれを送信するときに、 PasswordプロパティとSaltプロパティを公開することです。

それを書き込むが、APIユーザーに表示されたときに公開されないように設定できるデータ属性はありますか?

4

1 に答える 1

2

正しいアプローチは、ビューモデルを使用することです。ドメインエンティティをビューに渡さないでください。ビューの特定の要件を満たすビューモデルを設計します。したがって、たとえば、PasswordプロパティとSaltプロパティを持たないビューモデルを設計します。これは、このビューに必要なものだからです。次に、ドメインモデルとビューモデル間のマッピングを容易にするために、AutoMapperを使用できます。

ビューモデルのグッドプラクティスに従わない場合でも、POSTアクションをBind属性で乱雑にし、モデルバインディングに含める/除外するプロパティを決定する可能性があります。例えば:

[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
    ...
}
于 2012-09-11T15:36:27.773 に答える