MVC 安全性:ViewModel vs. [Bind()] 注释.两者都需要,或者一个或另一个就足够了



我一直在寻找这个问题的答案,因为我希望我的代码尽可能安全。

安全性方面,ViewModel[Bind()]是等价的吗?

详细解释

例如,假设您有以下模型:

型号.cs

public class Model
{
    public int Id { get; set; }
    [Required]
    [RegularExpression(Regex, ErrorMessage = RegexError)]
    [StringLength(20, MinimumLength = 2)]
    public string Something { get; set; }
    [Required]
    [RegularExpression(Regex, ErrorMessage = RegexError)]
    [StringLength(40, MinimumLength = 4)]
    public string SomethingElse { get; set; }
    [Required]
    [RegularExpression(Regex, ErrorMessage = RegexError)]
    [StringLength(60, MinimumLength = 8)]
    public string AnotherSomethingElse { get; set; }
}

模型控制器.cs

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Something([Bind(Include="Something,SomethingElse")] Model model)
    {
        // Do stuff here
    }

在这种情况下,我使用 [Bind()] 注释从Something(Model model)正在执行的任何操作中排除其他数据。我只允许我想要的输入。

但是,如果我改用ViewModel会发生什么?喜欢这个:

模型

视图模型.cs

public class ModelViewModel
{
    // Security annotations intentionally removed to keep question compact.
    public string Something { get; set; }
    public string SomethingElse { get; set; }
}

。我还需要在Something(Model model)中使用[Bind()]吗?它们是彼此独立的,还是在排除不需要的列进行更新时以相同的方式工作?

我误解了这是如何工作的吗?

两者绝对等效且足够安全。不过,使用ViewModel似乎更自然。无需保留允许绑定的属性的长字符串列表。视图模型执行此目的。如果使用视图模型,则不需要任何Bind()属性。视图模型的属性指示从请求中反序列化的内容。其他一切都被扔掉了。

相关内容

最新更新